Python 101 (1st Edition)
Python 101 (1st Edition)
About the Book
Note: This book has been replaced with a new edition.
Learn how to program with Python 3 from beginning to end. Python 101 starts off with the fundamentals of Python and then builds onto what you've learned from there. The audience of this book is primarily people who have programmed in the past but want to learn Python. This book covers a fair amount of intermediate level material in addition to the beginner material.
To cover all this information, the book is split into five parts.
Part One
The first part is the beginner section. In it you will learn all the basics of Python. From Python types (strings, lists, dictionaries) to conditional statements to loops. You will also learn about comprehensions, functions and classes and everything in between!
Part Two
This section will be a curated tour of the Python Standard Library. The intent isn't to cover everything in it, but instead it is to show the reader that you can do a lot with Python right out of the box. We'll be covering the modules I find the most useful in day-to-day programming tasks, such as os, sys, logging, threads, and more.
Part Three
An all intermediate section covering lambda, decorators, properties, debugging, testing and profiling.
Part Four
Now things get really interesting! In part four, we will be learning how to install 3rd party libraries (i.e. packages) from the Python Package Index and other locations. We will cover easy_install and pip. This section will also be a series of tutorials where you will learn how to use the packages you download. For example, you will learn how to download a file, parse XML, use an Object Relational Mapper to work with a database, etc.
Part Five
The last section of the book will cover how to share your code with your friends and the world! You will learn how to package it up and share it on the Python Package Index (i.e. how to create an egg or wheel). You will also learn how to create executables using py2exe, bb_freeze, cx_freeze and PyInstaller. Finally you will learn how to create an installer using Inno Setup.
Reader Testimonials

Nick Russo
Network Consulting Engineer (CCDE/CCIEx2)
Python programming is quickly becoming a critical skill for network engineers and architects. As a former-coder-turned-networker, I found this book to be refreshingly easy to read with succinct examples. I follow along step-by-step with Mike to code his examples and see the outputs for myself, which builds confidence. This is among the best resources for network engineers who need to brush up on their Python skills or learn Python for the first time. I highly recommend this book!
Table of Contents
-
Introduction
- A Brief History of Python
- About the Author
- Conventions
- Requirements
- Reader Feedback
- Errata
- Code Examples
- Part I - Learning the Basics
-
Chapter 1 - IDLE Programming
- Using IDLE
- Other Tips
- Wrapping Up
-
Chapter 2 - All About Strings
- How to Create a String
- String Concatenation
- String Methods
- String Slicing
- String Formatting
- Wrapping Up
-
Chapter 3 - Lists, Tuples and Dictionaries
- Lists
- Tuples
- Dictionaries
- Wrapping Up
-
Chapter 4 - Conditional Statements
- The if statement
- Boolean Operations
- Checking for Nothing
- Special Characters
- if __name__ == “__main__”
- Wrapping Up
-
Chapter 5 - Loops
- The for Loop
- The while Loop
- What else is for in loops
- Wrapping Up
-
Chapter 6 - Python Comprehensions
- List Comprehensions
- Dictionary Comprehensions
- Set Comprehensions
- Wrapping Up
-
Chapter 7 - Exception Handling
- Common Exceptions
- How to Handle Exceptions
- The finally Statement
- try, except, or else!
- Wrapping Up
-
Chapter 8 - Working with Files
- How to Read a File
- How To Read Files Piece by Piece
- How to Read a Binary File
- Writing Files in Python
- Using the with Operator
- Catching Errors
- Wrapping Up
-
Chapter 9 - Importing
- import this
- Using from to import
- Importing Everything!
- Wrapping Up
-
Chapter 10 - Functions
- An Empty Function (the stub)
- Passing Arguments to a Function
- Keyword Arguments
- *args and **kwargs
- A Note on Scope and Globals
- Coding Tips
- Wrapping Up
-
Chapter 11 - Classes
- Creating a Class
- What is self?
- Subclasses
- Wrapping Up
- Part II - Learning from the Library
-
Chapter 12 - Introspection
- The Python Type
- The Python Dir
- Python Help!
- Wrapping Up
-
Chapter 13 - The csv Module
- Reading a CSV File
- Writing a CSV File
- Wrapping Up
-
Chapter 14 - configparser
- Creating a Config File
- How to Read, Update and Delete Options
- How to Use Interpolation
- Wrapping Up
-
Chapter 15 - Logging
- Creating a Simple Logger
- How to log From Multiple Modules (and Formatting too!)
- Configuring Logs for Work and Pleasure
- Wrapping Up
-
Chapter 16 - The os Module
- os.name
- os.environ, os.getenv() and os.putenv()
- os.chdir() and os.getcwd()
- os.mkdir() and os.makedirs()
- os.remove() and os.rmdir()
- os.rename(src, dst)
- os.startfile()
- os.walk()
- os.path
- Wrapping Up
-
Chapter 17 - The email / smtplib Module
- Email Basics - How to Send an Email with smtplib
- Sending Multiple Emails at Once
- Send email using the TO, CC and BCC lines
- Add an attachment / body using the email module
- Wrapping Up
-
Chapter 18 - The sqlite Module
- How to Create a Database and INSERT Some Data
- Updating and Deleting Records
- Basic SQLite Queries
- Wrapping Up
-
Chapter 19 - The subprocess Module
- The call function
- The Popen Class
- Learning to Communicate
- Wrapping Up
-
Chapter 20 - The sys Module
- sys.argv
- sys.executable
- sys.exit
- sys.path
- sys.platform
- sys.stdin / stdout / stderr
- Wrapping Up
-
Chapter 21 - The threading module
- Using Threads
- Writing a Threaded Downloader
- Using Queues
- Wrapping Up
-
Chapter 22 - Working with Dates and Time
- The datetime Module
- datetime.date
- datetime.datetime
- datetime.timedelta
- The time Module
- time.ctime
- time.sleep
- time.strftime
- time.time
- Wrapping Up
-
Chapter 23 - The xml module
- Working with minidom
- Parsing with ElementTree
- How to Create XML with ElementTree
- How to Edit XML with ElementTree
- How to Parse XML with ElementTree
- Wrapping Up
- Part III - Intermediate Odds and Ends
-
Chapter 24 - The Python Debugger
- How to Start the Debugger
- Stepping Through the Code
- Setting breakpoints
- Wrapping Up
-
Chapter 25 - Decorators
- A Simple Function
- Creating a Logging Decorator
- Built-in Decorators
- @classmethod and @staticmethod
- Python Properties
- Replacing Setters and Getters with a Python property
- Wrapping Up
-
Chapter 26 - The lambda
- Tkinter + lambda
- Wrapping Up
-
Chapter 27 - Code Profiling
- Profiling Your Code with cProfile
- Wrapping Up
-
Chapter 28 - An Intro to Testing
- Testing with doctest
- Running doctest via the Terminal
- Running doctest Inside a Module
- Running doctest From a Separate File
- Test Driven Development with unittest
- The First Test
- The Second Test
- The Third (and Final) Test
- Other Notes
- Wrapping Up
- Part IV - Tips, Tricks and Tutorials
-
Chapter 29 - Installing Packages
- Installing from Source
- Using easy_install
- Using pip
- A Note on Dependencies
- Wrapping Up
-
Chapter 30 - ConfigObj
- Getting Started
- Using a configspec
- Wrapping Up
-
Chapter 31 - Parsing XML with lxml
- Parsing XML with lxml
- Parsing the Book Example
- Parsing XML with lxml.objectify
- Creating XML with lxml.objectify
- Wrapping Up
-
Chapter 32 - Python Code Analysis
- Getting Started with pylint
- Analyzing Your Code
- Getting Started with pyflakes
- Wrapping Up
-
Chapter 33 - The requests package
- Using requests
- How to Submit a Web Form
- Wrapping Up
-
Chapter 34 - SQLAlchemy
- How to Create a Database
- How to Insert / Add Data to Your Tables
- How to Modify Records with SQLAlchemy
- How to Delete Records in SQLAlchemy
- The Basic SQL Queries of SQLAlchemy
- Wrapping Up
-
Chapter 35 - virtualenv
- Installation
- Creating a Virtual Environment
- Wrapping Up
- Part V - Packaging and Distribution
-
Chapter 36 - Creating Modules and Packages
- How to Create a Python Module
- How to Create a Python Package
- Wrapping Up
-
Chapter 37 - How to Add Your Code to PyPI
- Creating a setup.py File
- Registering Packages
- Uploading Packages to PyPI
- Wrapping Up
-
Chapter 38 - The Python egg
- Creating an egg
- Wrapping Up
-
Chapter 39 - Python wheels
- Getting Started
- Creating a wheel
- Installing a Python wheel
- Wrapping Up
-
Chapter 40 - py2exe
- Creating a Simple GUI
- The py2exe setup.py file
- Creating an Advanced setup.py File
- Wrapping Up
-
Chapter 41 - bbfreeze
- Getting Started with bbfreeze
- Using bbfreeze’s Advanced Configuration
- Wrapping Up
-
Chapter 42 - cx_Freeze
- Getting Started with cx_Freeze
- Advanced cx_Freeze - Using a setup.py File
- Wrapping Up
-
Chapter 43 - PyInstaller
- Getting Started with PyInstaller
- PyInstaller and wxPython
- Wrapping Up
-
Chapter 44 - Creating an Installer
- Getting Started with GUI2Exe
- Let’s Make an Installer!
- Wrapping Up
-
Appendix A: Putting It All Together
- The Background
- The Specification
- Breaking the Specification Down
- Turning Chapters Into a Book
- Reading the Customer CSV File
- Emailing the PDF
- Putting it all Together
- Wrapping Up
The Leanpub 60-day 100% Happiness Guarantee
Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.
See full terms
80% Royalties. Earn $16 on a $20 book.
We pay 80% royalties. That's not a typo: you earn $16 on a $20 sale. If we sell 5000 non-refunded copies of your book or course for $20, you'll earn $80,000.
(Yes, some authors have already earned much more than that on Leanpub.)
In fact, authors have earned$12,307,240writing, publishing and selling on Leanpub.
Learn more about writing on Leanpub
Free Updates. DRM Free.
If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).
Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.
Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.
Learn more about Leanpub's ebook formats and where to read them
Top Books
OpenIntro Statistics
David Diez, Christopher Barr, Mine Cetinkaya-Rundel, and OpenIntroA complete foundation for Statistics, also serving as a foundation for Data Science.
Leanpub revenue supports OpenIntro (US-based nonprofit) so we can provide free desk copies to teachers interested in using OpenIntro Statistics in the classroom and expand the project to support free textbooks in other subjects.
More resources: openintro.org.
Personal Finance
Jason AndersonThis textbook provides an in-depth analysis on personal finance that is both practical and straightforward in its approach. It has been written in such a way that the readers can gain knowledge without getting overwhelmed by the technical terms. Suitable for both beginners and advanced learners.
Getting to Know IntelliJ IDEA
Trisha Gee and Helen ScottIf we treat our IDE as a text editor, we are doing ourselves a disservice. Using a combination of tutorials and a questions-and-answers approach, Getting to Know IntelliJ IDEA will help you find ways to use IntelliJ IDEA that enable you to work comfortably and productively as a professional developer.
R Programming for Data Science
Roger D. PengThis book brings the fundamentals of R programming to you, using the same material developed as part of the industry-leading Johns Hopkins Data Science Specialization. The skills taught in this book will lay the foundation for you to begin your journey learning data science. Printed copies of this book are available through Lulu.
C++20 - The Complete Guide
Nicolai M. JosuttisAll new language and library features of C++20 (for those who know previous C++ versions).
The book presents all new language and library features of C++20. Learn how this impacts day-to-day programming, to benefit in practice, to combine new features, and to avoid all new traps.
Buy early, pay less, free updates.
Other books:
Mastering STM32 - Second Edition
Carmine NovielloWith more than 1200 microcontrollers, STM32 is probably the most complete ARM Cortex-M platform on the market. This book aims to be the most complete guide around introducing the reader to this exciting MCU portfolio from ST Microelectronics and its official CubeHAL and STM32CubeIDE development environment.
Stats One
William FooteMachine Learning Q and AI
Sebastian Raschka, PhDHave you recently completed a machine learning or deep learning course and wondered what to learn next? With 30 questions and answers on key concepts in machine learning and AI, this book provides bite-sized bits of knowledge for your journey to becoming a machine learning expert.
Ansible for DevOps
Jeff GeerlingAnsible is a simple, but powerful, server and configuration management tool. Learn to use Ansible effectively, whether you manage one server—or thousands.
Gradual Modularization for Ruby and Rails
Stephan HagemannGet yourself a new tool to manage your Rails application and your growing engineering organization! Prevent the ball-of-mud (and fix it!). Go for microservices or SOA if it makes sense not just because you don't have any other tool. Do all this through a low-overhead tool: packages. Enable better conversations to make practical changes today.
Top Bundles
- #1
Software Architecture
2 Books
"Software Architecture for Developers" is a practical and pragmatic guide to modern, lightweight software architecture, specifically aimed at developers. You'll learn:The essence of software architecture.Why the software architecture role should include coding, coaching and collaboration.The things that you really need to think about before... - #2
CCIE Service Provider Ultimate Study Bundle
2 Books
Piotr Jablonski, Lukasz Bromirski, and Nick Russo have joined forces to deliver the only CCIE Service Provider training resource you'll ever need. This bundle contains a detailed and challenging collection of workbook labs, plus an extensively detailed technical reference guide. All of us have earned the CCIE Service Provider certification... - #3
1500 QUIZ COMMENTATI (3 libri)
3 Books
Tre libri dei QUIZ MMG Commentati al prezzo di DUE! I QUIZ dei concorsi ufficiali di Medicina Generale relativi agli anni: 2000-2001-2003-2012-2013-2014-2015-2016-2017-2018-2019-2020-2021 +100 inediti Raccolti in unico bundle per aiutarvi nello studio e nella preparazione al concorso. All'interno di ogni libro i quiz sono stati suddivisi per... - #4
Pattern-Oriented Memory Forensics and Malware Detection
2 Books
This training bundle for security engineers and researchers, malware and memory forensics analysts includes two accelerated training courses for Windows memory dump analysis using WinDbg. It is also useful for technical support and escalation engineers who analyze memory dumps from complex software environments and need to check for possible... - #5
Practical FP in Scala + Functional event-driven architecture
2 Books
Practical FP in Scala (A hands-on approach) & Functional event-driven architecture, aka FEDA, (Powered by Scala 3), together as a bundle! The content of PFP in Scala is a requirement to understand FEDA so why not take advantage of this bundle!? - #7
Linux Administration Complet
4 Books
Ce lot comprend les quatre volumes du Guide Linux Administration :Linux Administration, Volume 1, Administration fondamentale : Guide pratique de préparation aux examens de certification LPIC 1, Linux Essentials, RHCSA et LFCS. Administration fondamentale. Introduction à Linux. Le Shell. Traitement du texte. Arborescence de fichiers. Sécurité... - #9
Development and Deployment of Multiplayer Online Games, Part ARCH. Architecture (Vol. I-III)
3 Books
What's the Big Idea? The idea behind this book is to summarize the body of knowledge that already exists on multiplayer games but is not available in one single place.And quite a fewof the issues discussed within this series (planned as three nine volumes ~300 pages each), while known in the industry, have not been published at all (except for... - #10
Modern C++ Collection
3 Books
Get All about Modern C++C++ Standard Library, including C++20Concurrency with Modern C++, including C++20C++20Each book has about 200 complete code examples. Updates are included. When I update one of the books, you immediately get the updated bundle. You can expect significant updates to each new C++ standard (C++23, C++26, .. ) and also...