🔙 Quay lại trang tải sách pdf ebook Automate the boring stuff with python 2nd edition
Ebooks
Nhóm Zalo
AUTOMATE THE BORING STUFF WITH PYTHON
2ND EDITION
Practical Programming for Total Beginners
by Al Sweigart
San Francisco
AUTOMATE THE BORING STUFF WITH PYTHON, 2ND EDITION. Copyright © 2020 by Al Sweigart.
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher.
ISBN-10: 1-59327-992-2
ISBN-13: 978-1-59327-992-9
Publisher: William Pollock
Production Editor: Laurel Chun
Cover Illustration: Josh Ellingson
Interior Design: Octopod Studios
Developmental Editors: Frances Saux and Jan Cash
Technical Reviewers: Ari Lacenski and Philip James
Copyeditors: Kim Wimpsett, Britt Bogan, and Paula L. Fleming
Compositors: Susan Glinert Stevens and Danielle Foster
Proofreaders: Lisa Devoto Farrell and Emelie Burnette
Indexer: BIM Indexing and Proofreading Services
For information on distribution, translations, or bulk sales,
please contact No Starch Press, Inc. directly:
No Starch Press, Inc.
245 8th Street, San Francisco, CA 94103
phone: 1.415.863.9900; [email protected]
www.nostarch.com
The Library of Congress Control Number for the first edition is: 2014953114
No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it.
This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 United States License. To view a copy of this license, visit
http://creativecommons.org/licenses/by-nc-sa/3.0/us/ or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
For my nephew Jack
About the Author
Al Sweigart is a software developer and tech book author. Python is his favorite programming language, and he is the developer of several open source modules for it. His other books are freely available under a Creative Commons license on his website https://inventwithpython.com/. His cat now weighs 11 pounds.
About the Tech Reviewer
Philip James has been working in Python for over a decade and is a frequent speaker in the Python community. He speaks on topics ranging from Unix fundamentals to open source social networks. Philip is a Core Contributor to the BeeWare project and lives in the San Francisco Bay Area with his partner Nic and her cat River.
BRIEF CONTENTS
Acknowledgments
Introduction
PART I: PYTHON PROGRAMMING BASICS Chapter 1: Python Basics
Chapter 2: Flow Control
Chapter 3: Functions
Chapter 4: Lists
Chapter 5: Dictionaries and Structuring Data Chapter 6: Manipulating Strings
PART II: AUTOMATING TASKS
Chapter 7: Pattern Matching with Regular Expressions Chapter 8: Input Validation
Chapter 9: Reading and Writing Files
Chapter 10: Organizing Files
Chapter 11: Debugging
Chapter 12: Web Scraping
Chapter 13: Working with Excel Spreadsheets Chapter 14: Working with Google Sheets Chapter 15: Working with PDF and Word Documents Chapter 16: Working with CSV Files and JSON Data
Chapter 17: Keeping Time, Scheduling Tasks, and Launching Programs Chapter 18: Sending Email and Text Messages
Chapter 19: Manipulating Images
Chapter 20: Controlling the Keyboard and Mouse with GUI Automation
Appendix A: Installing Third-Party Modules
Appendix B: Running Programs
Appendix C: Answers to the Practice Questions
Index
CONTENTS IN DETAIL
ACKNOWLEDGMENTS
INTRODUCTION
Whom Is This Book For?
Conventions
What Is Programming?
What Is Python?
Programmers Don’t Need to Know Much Math You Are Not Too Old to Learn Programming Programming Is a Creative Activity
About This Book
Downloading and Installing Python
Downloading and Installing Mu
Starting Mu
Starting IDLE
The Interactive Shell
Installing Third-Party Modules
How to Find Help
Asking Smart Programming Questions
Summary
PART I: PYTHON PROGRAMMING BASICS
1
PYTHON BASICS
Entering Expressions into the Interactive Shell The Integer, Floating-Point, and String Data Types String Concatenation and Replication
Storing Values in Variables
Assignment Statements
Variable Names
Your First Program
Dissecting Your Program
Comments
The print() Function
The input() Function
Printing the User’s Name
The len() Function
The str(), int(), and float() Functions Summary
Practice Questions
2
FLOW CONTROL
Boolean Values
Comparison Operators
Boolean Operators
Binary Boolean Operators
The not Operator
Mixing Boolean and Comparison Operators Elements of Flow Control
Conditions
Blocks of Code
Program Execution
Flow Control Statements
if Statements
else Statements
elif Statements
while Loop Statements
break Statements
continue Statements
for Loops and the range() Function
Importing Modules
from import Statements
Ending a Program Early with the sys.exit() Function A Short Program: Guess the Number
A Short Program: Rock, Paper, Scissors
Summary
Practice Questions
3
FUNCTIONS
def Statements with Parameters
Define, Call, Pass, Argument, Parameter
Return Values and return Statements
The None Value
Keyword Arguments and the print() Function
The Call Stack
Local and Global Scope
Local Variables Cannot Be Used in the Global Scope Local Scopes Cannot Use Variables in Other Local Scopes Global Variables Can Be Read from a Local Scope Local and Global Variables with the Same Name
The global Statement
Exception Handling
A Short Program: Zigzag
Summary
Practice Questions
Practice Projects
The Collatz Sequence
Input Validation
4
LISTS
The List Data Type
Getting Individual Values in a List with Indexes
Negative Indexes
Getting a List from Another List with Slices
Getting a List’s Length with the len() Function
Changing Values in a List with Indexes
List Concatenation and List Replication
Removing Values from Lists with del Statements
Working with Lists
Using for Loops with Lists
The in and not in Operators
The Multiple Assignment Trick
Using the enumerate() Function with Lists
Using the random.choice() and random.shuffle() Functions with Lists
Augmented Assignment Operators
Methods
Finding a Value in a List with the index() Method
Adding Values to Lists with the append() and insert() Methods Removing Values from Lists with the remove() Method Sorting the Values in a List with the sort() Method
Reversing the Values in a List with the reverse() Method Example Program: Magic 8 Ball with a List
Sequence Data Types
Mutable and Immutable Data Types
The Tuple Data Type
Converting Types with the list() and tuple() Functions References
Identity and the id() Function
Passing References
The copy Module’s copy() and deepcopy() Functions
A Short Program: Conway’s Game of Life
Summary
Practice Questions
Practice Projects
Comma Code
Coin Flip Streaks
Character Picture Grid
5
DICTIONARIES AND STRUCTURING DATA The Dictionary Data Type
Dictionaries vs. Lists
The keys(), values(), and items() Methods
Checking Whether a Key or Value Exists in a Dictionary The get() Method
The setdefault() Method
Pretty Printing
Using Data Structures to Model Real-World Things A Tic-Tac-Toe Board
Nested Dictionaries and Lists
Summary
Practice Questions
Practice Projects
Chess Dictionary Validator
Fantasy Game Inventory
List to Dictionary Function for Fantasy Game Inventory
6
MANIPULATING STRINGS
Working with Strings
String Literals
Indexing and Slicing Strings
The in and not in Operators with Strings
Putting Strings Inside Other Strings
Useful String Methods
The upper(), lower(), isupper(), and islower() Methods
The isX() Methods
The startswith() and endswith() Methods
The join() and split() Methods
Splitting Strings with the partition() Method
Justifying Text with the rjust(), ljust(), and center() Methods Removing Whitespace with the strip(), rstrip(), and lstrip() Methods
Numeric Values of Characters with the ord() and chr() Functions Copying and Pasting Strings with the pyperclip Module Project: Multi-Clipboard Automatic Messages
Step 1: Program Design and Data Structures
Step 2: Handle Command Line Arguments
Step 3: Copy the Right Phrase
Project: Adding Bullets to Wiki Markup
Step 1: Copy and Paste from the Clipboard
Step 2: Separate the Lines of Text and Add the Star
Step 3: Join the Modified Lines
A Short Progam: Pig Latin
Summary
Practice Questions
Practice Projects
Table Printer
Zombie Dice Bots
PART II: AUTOMATING TASKS
7
PATTERN MATCHING WITH REGULAR EXPRESSIONS Finding Patterns of Text Without Regular Expressions Finding Patterns of Text with Regular Expressions
Creating Regex Objects
Matching Regex Objects
Review of Regular Expression Matching
More Pattern Matching with Regular Expressions Grouping with Parentheses
Matching Multiple Groups with the Pipe
Optional Matching with the Question Mark
Matching Zero or More with the Star
Matching One or More with the Plus
Matching Specific Repetitions with Braces
Greedy and Non-greedy Matching
The findall() Method
Character Classes
Making Your Own Character Classes
The Caret and Dollar Sign Characters
The Wildcard Character
Matching Everything with Dot-Star
Matching Newlines with the Dot Character
Review of Regex Symbols
Case-Insensitive Matching
Substituting Strings with the sub() Method
Managing Complex Regexes
Combining re.IGNORECASE, re.DOTALL, and re.VERBOSE Project: Phone Number and Email Address Extractor Step 1: Create a Regex for Phone Numbers
Step 2: Create a Regex for Email Addresses
Step 3: Find All Matches in the Clipboard Text
Step 4: Join the Matches into a String for the Clipboard Running the Program
Ideas for Similar Programs
Summary
Practice Questions
Practice Projects
Date Detection
Strong Password Detection
Regex Version of the strip() Method
8
INPUT VALIDATION
The PyInputPlus Module
The min, max, greaterThan, and lessThan Keyword Arguments
The blank Keyword Argument
The limit, timeout, and default Keyword Arguments The allowRegexes and blockRegexes Keyword Arguments Passing a Custom Validation Function to inputCustom() Project: How to Keep an Idiot Busy for Hours
Project: Multiplication Quiz
Summary
Practice Questions
Practice Projects
Sandwich Maker
Write Your Own Multiplication Quiz
9
READING AND WRITING FILES
Files and File Paths
Backslash on Windows and Forward Slash on macOS and Linux
Using the / Operator to Join Paths
The Current Working Directory
The Home Directory
Absolute vs. Relative Paths
Creating New Folders Using the os.makedirs() Function Handling Absolute and Relative Paths
Getting the Parts of a File Path
Finding File Sizes and Folder Contents
Modifying a List of Files Using Glob Patterns
Checking Path Validity
The File Reading/Writing Process
Opening Files with the open() Function
Reading the Contents of Files
Writing to Files
Saving Variables with the shelve Module
Saving Variables with the pprint.pformat() Function Project: Generating Random Quiz Files
Step 1: Store the Quiz Data in a Dictionary
Step 2: Create the Quiz File and Shuffle the Question Order Step 3: Create the Answer Options
Step 4: Write Content to the Quiz and Answer Key Files Project: Updatable Multi-Clipboard
Step 1: Comments and Shelf Setup
Step 2: Save Clipboard Content with a Keyword
Step 3: List Keywords and Load a Keyword’s Content Summary
Practice Questions
Practice Projects
Extending the Multi-Clipboard
Mad Libs
Regex Search
10
ORGANIZING FILES
The shutil Module
Copying Files and Folders
Moving and Renaming Files and Folders
Permanently Deleting Files and Folders
Safe Deletes with the send2trash Module
Walking a Directory Tree
Compressing Files with the zipfile Module
Reading ZIP Files
Extracting from ZIP Files
Creating and Adding to ZIP Files
Project: Renaming Files with American-Style Dates to European-Style Dates
Step 1: Create a Regex for American-Style Dates
Step 2: Identify the Date Parts from the Filenames
Step 3: Form the New Filename and Rename the Files Ideas for Similar Programs
Project: Backing Up a Folder into a ZIP File
Step 1: Figure Out the ZIP File’s Name
Step 2: Create the New ZIP File
Step 3: Walk the Directory Tree and Add to the ZIP File Ideas for Similar Programs
Summary
Practice Questions
Practice Projects
Selective Copy
Deleting Unneeded Files
Filling in the Gaps
11
DEBUGGING
Raising Exceptions
Getting the Traceback as a String
Assertions
Using an Assertion in a Traffic Light Simulation
Logging
Using the logging Module
Don’t Debug with the print() Function
Logging Levels
Disabling Logging
Logging to a File
Mu’s Debugger
Continue
Step In
Step Over
Step Out
Stop
Debugging a Number Adding Program
Breakpoints
Summary
Practice Questions
Practice Project
Debugging Coin Toss
12
WEB SCRAPING
Project: mapIt.py with the webbrowser Module
Step 1: Figure Out the URL
Step 2: Handle the Command Line Arguments
Step 3: Handle the Clipboard Content and Launch the Browser
Ideas for Similar Programs
Downloading Files from the Web with the requests Module Downloading a Web Page with the requests.get() Function Checking for Errors
Saving Downloaded Files to the Hard Drive
HTML
Resources for Learning HTML
A Quick Refresher
Viewing the Source HTML of a Web Page
Opening Your Browser’s Developer Tools
Using the Developer Tools to Find HTML Elements Parsing HTML with the bs4 Module
Creating a BeautifulSoup Object from HTML
Finding an Element with the select() Method
Getting Data from an Element’s Attributes
Project: Opening All Search Results
Step 1: Get the Command Line Arguments and Request the Search Page
Step 2: Find All the Results
Step 3: Open Web Browsers for Each Result
Ideas for Similar Programs
Project: Downloading All XKCD Comics
Step 1: Design the Program
Step 2: Download the Web Page
Step 3: Find and Download the Comic Image
Step 4: Save the Image and Find the Previous Comic Ideas for Similar Programs
Controlling the Browser with the selenium Module Starting a selenium-Controlled Browser
Finding Elements on the Page
Clicking the Page
Filling Out and Submitting Forms
Sending Special Keys
Clicking Browser Buttons
More Information on Selenium
Summary
Practice Questions
Practice Projects
Command Line Emailer
Image Site Downloader
2048
Link Verification
13
WORKING WITH EXCEL SPREADSHEETS
Excel Documents
Installing the openpyxl Module
Reading Excel Documents
Opening Excel Documents with OpenPyXL
Getting Sheets from the Workbook
Getting Cells from the Sheets
Converting Between Column Letters and Numbers
Getting Rows and Columns from the Sheets
Workbooks, Sheets, Cells
Project: Reading Data from a Spreadsheet
Step 1: Read the Spreadsheet Data
Step 2: Populate the Data Structure
Step 3: Write the Results to a File
Ideas for Similar Programs
Writing Excel Documents
Creating and Saving Excel Documents
Creating and Removing Sheets
Writing Values to Cells
Project: Updating a Spreadsheet
Step 1: Set Up a Data Structure with the Update Information Step 2: Check All Rows and Update Incorrect Prices
Ideas for Similar Programs
Setting the Font Style of Cells
Font Objects
Formulas
Adjusting Rows and Columns
Setting Row Height and Column Width
Merging and Unmerging Cells
Freezing Panes
Charts
Summary
Practice Questions
Practice Projects
Multiplication Table Maker
Blank Row Inserter
Spreadsheet Cell Inverter
Text Files to Spreadsheet
Spreadsheet to Text Files
14
WORKING WITH GOOGLE SHEETS
Installing and Setting Up EZSheets
Obtaining Credentials and Token Files
Revoking the Credentials File
Spreadsheet Objects
Creating, Uploading, and Listing Spreadsheets Spreadsheet Attributes
Downloading and Uploading Spreadsheets
Deleting Spreadsheets
Sheet Objects
Reading and Writing Data
Creating and Deleting Sheets
Copying Sheets
Working with Google Sheets Quotas
Summary
Practice Questions
Practice Projects
Downloading Google Forms Data
Converting Spreadsheets to Other Formats
Finding Mistakes in a Spreadsheet
15
WORKING WITH PDF AND WORD DOCUMENTS PDF Documents
Extracting Text from PDFs
Decrypting PDFs
Creating PDFs
Project: Combining Select Pages from Many PDFs Step 1: Find All PDF Files
Step 2: Open Each PDF
Step 3: Add Each Page
Step 4: Save the Results
Ideas for Similar Programs
Word Documents
Reading Word Documents
Getting the Full Text from a .docx File
Styling Paragraph and Run Objects
Creating Word Documents with Nondefault Styles Run Attributes
Writing Word Documents
Adding Headings
Adding Line and Page Breaks
Adding Pictures
Creating PDFs from Word Documents
Summary
Practice Questions
Practice Projects
PDF Paranoia
Custom Invitations as Word Documents
Brute-Force PDF Password Breaker
16
WORKING WITH CSV FILES AND JSON DATA The csv Module
reader Objects
Reading Data from reader Objects in a for Loop writer Objects
The delimiter and lineterminator Keyword Arguments DictReader and DictWriter CSV Objects
Project: Removing the Header from CSV Files
Step 1: Loop Through Each CSV File
Step 2: Read in the CSV File
Step 3: Write Out the CSV File Without the First Row
Ideas for Similar Programs
JSON and APIs
The json Module
Reading JSON with the loads() Function
Writing JSON with the dumps() Function
Project: Fetching Current Weather Data
Step 1: Get Location from the Command Line Argument Step 2: Download the JSON Data
Step 3: Load JSON Data and Print Weather
Ideas for Similar Programs
Summary
Practice Questions
Practice Project
Excel-to-CSV Converter
17
KEEPING TIME, SCHEDULING TASKS, AND LAUNCHING PROGRAMS
The time Module
The time.time() Function
The time.sleep() Function
Rounding Numbers
Project: Super Stopwatch
Step 1: Set Up the Program to Track Times
Step 2: Track and Print Lap Times
Ideas for Similar Programs
The datetime Module
The timedelta Data Type
Pausing Until a Specific Date
Converting datetime Objects into Strings
Converting Strings into datetime Objects
Review of Python’s Time Functions
Multithreading
Passing Arguments to the Thread’s Target Function Concurrency Issues
Project: Multithreaded XKCD Downloader
Step 1: Modify the Program to Use a Function
Step 2: Create and Start Threads
Step 3: Wait for All Threads to End
Launching Other Programs from Python
Passing Command Line Arguments to the Popen() Function Task Scheduler, launchd, and cron
Opening Websites with Python
Running Other Python Scripts
Opening Files with Default Applications
Project: Simple Countdown Program
Step 1: Count Down
Step 2: Play the Sound File
Ideas for Similar Programs
Summary
Practice Questions
Practice Projects
Prettified Stopwatch
Scheduled Web Comic Downloader
18
SENDING EMAIL AND TEXT MESSAGES
Sending and Receiving Email with the Gmail API
Enabling the Gmail API
Sending Mail from a Gmail Account
Reading Mail from a Gmail Account
Searching Mail from a Gmail Account
Downloading Attachments from a Gmail Account
SMTP
Sending Email
Connecting to an SMTP Server
Sending the SMTP “Hello” Message
Starting TLS Encryption
Logging In to the SMTP Server
Sending an Email
Disconnecting from the SMTP Server
IMAP
Retrieving and Deleting Emails with IMAP Connecting to an IMAP Server
Logging In to the IMAP Server
Searching for Email
Fetching an Email and Marking It as Read Getting Email Addresses from a Raw Message Getting the Body from a Raw Message
Deleting Emails
Disconnecting from the IMAP Server
Project: Sending Member Dues Reminder Emails Step 1: Open the Excel File
Step 2: Find All Unpaid Members
Step 3: Send Customized Email Reminders Sending Text Messages with SMS Email Gateways Sending Text Messages with Twilio
Signing Up for a Twilio Account
Sending Text Messages
Project: “Just Text Me” Module
Summary
Practice Questions
Practice Projects
Random Chore Assignment Emailer
Umbrella Reminder
Auto Unsubscriber
Controlling Your Computer Through Email
19
MANIPULATING IMAGES
Computer Image Fundamentals
Colors and RGBA Values
Coordinates and Box Tuples
Manipulating Images with Pillow
Working with the Image Data Type
Cropping Images
Copying and Pasting Images onto Other Images
Resizing an Image
Rotating and Flipping Images
Changing Individual Pixels
Project: Adding a Logo
Step 1: Open the Logo Image
Step 2: Loop Over All Files and Open Images
Step 3: Resize the Images
Step 4: Add the Logo and Save the Changes
Ideas for Similar Programs
Drawing on Images
Drawing Shapes
Drawing Text
Summary
Practice Questions
Practice Projects
Extending and Fixing the Chapter Project Programs
Identifying Photo Folders on the Hard Drive
Custom Seating Cards
20
CONTROLLING THE KEYBOARD AND MOUSE WITH GUI AUTOMATION
Installing the pyautogui Module
Setting Up Accessibility Apps on macOS
Staying on Track
Pauses and Fail-Safes
Shutting Down Everything by Logging Out Controlling Mouse Movement
Moving the Mouse
Getting the Mouse Position
Controlling Mouse Interaction
Clicking the Mouse
Dragging the Mouse
Scrolling the Mouse
Planning Your Mouse Movements
Working with the Screen
Getting a Screenshot
Analyzing the Screenshot
Image Recognition
Getting Window Information
Obtaining the Active Window
Other Ways of Obtaining Windows
Manipulating Windows
Controlling the Keyboard
Sending a String from the Keyboard
Key Names
Pressing and Releasing the Keyboard
Hotkey Combinations
Setting Up Your GUI Automation Scripts Review of the PyAutoGUI Functions
Project: Automatic Form Filler
Step 1: Figure Out the Steps
Step 2: Set Up Coordinates
Step 3: Start Typing Data
Step 4: Handle Select Lists and Radio Buttons Step 5: Submit the Form and Wait
Displaying Message Boxes
Summary
Practice Questions
Practice Projects
Looking Busy
Using the Clipboard to Read a Text Field Instant Messenger Bot
Game-Playing Bot Tutorial
A
INSTALLING THIRD-PARTY MODULES The pip Tool
Installing Third-Party Modules
Installing Modules for the Mu Editor
B
RUNNING PROGRAMS
Running Programs from the Terminal Window Running Python Programs on Windows Running Python Programs on macOS
Running Python Programs on Ubuntu Linux Running Python Programs with Assertions Disabled
C
ANSWERS TO THE PRACTICE QUESTIONS Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 7
Chapter 8
Chapter 9
Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Chapter 18 Chapter 19 Chapter 20
INDEX
ACKNOWLEDGMENTS
It’s misleading to have just my name on the cover. I couldn’t have written a book like this without the help of a lot of people. I’d like to thank my publisher, Bill Pollock; my editors, Laurel Chun, Leslie Shen, Greg Poulos, Jennifer Griffith-Delgado, and Frances Saux; and the rest of the staff at No Starch Press for their invaluable help. Thanks to my tech reviewers, Ari Lacenski and Philip James, for great suggestions, edits, and support.
Many thanks to everyone at the Python Software Foundation for their great work. The Python community is the best one I’ve found in the tech industry.
Finally, I would like to thank my family, friends, and the gang at Shotwell’s for not minding the busy life I’ve had while writing this book. Cheers!
INTRODUCTION
“You’ve just done in two hours what it takes the three of us two days to do.” My college roommate was working at a retail electronics store in the early 2000s. Occasionally, the store would receive a spreadsheet of thousands of product prices from other stores. A team of three employees would print the spreadsheet onto a thick stack of paper and split it among themselves. For each product price, they would look up their store’s price and note all the products that their competitors sold for less. It usually took a couple of days.
“You know, I could write a program to do that if you have the original file for the printouts,” my roommate told them, when he saw them sitting on the floor with papers scattered and stacked all around.
After a couple of hours, he had a short program that read a competitor’s price from a file, found the product in the store’s database, and noted whether the competitor was cheaper. He was still new to programming, so he spent most of his time looking up documentation in a programming book. The actual program took only a few seconds to run. My roommate and his co-workers took an extra-long lunch that day.
This is the power of computer programming. A computer is like a Swiss Army knife that you can configure for countless tasks. Many people spend hours clicking and typing to perform repetitive tasks,
unaware that the machine they’re using could do their job in seconds if they gave it the right instructions.
Whom Is This Book For?
Software is at the core of so many of the tools we use today: nearly everyone uses social networks to communicate, many people have internet-connected computers in their phones, and most office jobs involve interacting with a computer to get work done. As a result, the demand for people who can code has skyrocketed. Countless books, interactive web tutorials, and developer boot camps promise to turn ambitious beginners into software engineers with six-figure salaries.
This book is not for those people. It’s for everyone else. On its own, this book won’t turn you into a professional software developer any more than a few guitar lessons will turn you into a rock star. But if you’re an office worker, administrator, academic, or anyone else who uses a computer for work or fun, you will learn the basics of programming so that you can automate simple tasks such as these:
Moving and renaming thousands of files and sorting them into folders
Filling out online forms—no typing required
Downloading files or copying text from a website whenever it updates
Having your computer text you custom notifications
Updating or formatting Excel spreadsheets
Checking your email and sending out prewritten responses
These tasks are simple but time-consuming for humans, and they’re often so trivial or specific that there’s no ready-made software to perform them. Armed with a little bit of programming knowledge, however, you can have your computer do these tasks for you.
Conventions
This book is not designed as a reference manual; it’s a guide for beginners. The coding style sometimes goes against best practices (for example, some programs use global variables), but that’s a trade-off to make the code simpler to learn. This book is made for people to write throwaway code, so there’s not much time spent on style and elegance. Sophisticated programming concepts—like object-oriented programming, list comprehensions, and generators—aren’t covered because of the complexity they add. Veteran programmers may point out ways the code in this book could be changed to improve efficiency, but this book is mostly concerned with getting programs to work with the least amount of effort on your part.
What Is Programming?
Television shows and films often show programmers furiously typing cryptic streams of 1s and 0s on glowing screens, but modern programming isn’t that mysterious. Programming is simply the act of entering instructions for the computer to perform. These instructions might crunch some numbers, modify text, look up information in files, or communicate with other computers over the internet.
All programs use basic instructions as building blocks. Here are a few of the most common ones, in English:
“Do this; then do that.”
“If this condition is true, perform this action; otherwise, do that action.”
“Do this action exactly 27 times.”
“Keep doing that until this condition is true.”
You can combine these building blocks to implement more intricate decisions, too. For example, here are the programming instructions, called the source code, for a simple program written in the Python programming language. Starting at the top, the Python software runs
each line of code (some lines are run only if a certain condition is true or else Python runs some other line) until it reaches the bottom.
➊ passwordFile = open('SecretPasswordFile.txt')
➋ secretPassword = passwordFile.read()
➌ print('Enter your password.')
typedPassword = input()
➍ if typedPassword == secretPassword:
➎ print('Access granted')
➏ if typedPassword == '12345':
➐ print('That password is one that an idiot puts on their luggage.') else:
➑ print('Access denied')
You might not know anything about programming, but you could probably make a reasonable guess at what the previous code does just by reading it. First, the file SecretPasswordFile.txt is opened ➊, and the secret password in it is read ➋. Then, the user is prompted to input a password (from the keyboard) ➌. These two passwords are compared ➍, and if they’re the same, the program prints Access granted to the screen ➎. Next, the program checks to see whether the password is 12345 ➏ and hints that this choice might not be the best for a password ➐. If the passwords are not the same, the program prints Access denied to the screen ➑.
What Is Python?
Python is a programming language (with syntax rules for writing what is considered valid Python code) and the Python interpreter software that reads source code (written in the Python language) and performs its instructions. You can download the Python interpreter for free at https://python.org/, and there are versions for Linux, macOS, and Windows.
The name Python comes from the surreal British comedy group Monty Python, not from the snake. Python programmers are affectionately called Pythonistas, and both Monty Python and
serpentine references usually pepper Python tutorials and documentation.
Programmers Don’t Need to Know Much Math
The most common anxiety I hear about learning to program is the notion that it requires a lot of math. Actually, most programming doesn’t require math beyond basic arithmetic. In fact, being good at programming isn’t that different from being good at solving Sudoku puzzles.
To solve a Sudoku puzzle, the numbers 1 through 9 must be filled in for each row, each column, and each 3×3 interior square of the full 9×9 board. Some numbers are provided to give you a start, and you find a solution by making deductions based on these numbers. In the puzzle shown in Figure 0-1, since 5 appears in the first and second rows, it cannot show up in these rows again. Therefore, in the upper-right grid, it must be in the third row. Since the last column also already has a 5 in it, the 5 cannot go to the right of the 6, so it must go to the left of the 6. Solving one row, column, or square will provide more clues to the rest of the puzzle, and as you fill in one group of numbers 1 to 9 and then another, you’ll soon solve the entire grid.
Figure 0-1: A new Sudoku puzzle (left) and its solution (right). Despite using numbers, Sudoku doesn’t involve much math. (Images © Wikimedia Commons)
Just because Sudoku involves numbers doesn’t mean you have to be good at math to figure out the solution. The same is true of programming. Like solving a Sudoku puzzle, writing programs involves breaking down a problem into individual, detailed steps. Similarly, when debugging programs (that is, finding and fixing errors), you’ll patiently observe what the program is doing and find the cause of the bugs. And like all skills, the more you program, the better you’ll become.
You Are Not Too Old to Learn Programming
The second most common anxiety I hear about learning to program is that people think they’re too old to learn it. I read many internet comments from folks who think it’s too late for them because they are already (gasp!) 23 years old. This is clearly not “too old” to learn to program: many people learn much later in life.
You don’t need to have started as a child to become a capable programmer. But the image of programmers as whiz kids is a persistent one. Unfortunately, I contribute to this myth when I tell others that I was in grade school when I started programming.
However, programming is much easier to learn today than it was in the 1990s. Today, there are more books, better search engines, and many more online question-and-answer websites. On top of that, the programming languages themselves are far more user-friendly. For these reasons, everything I learned about programming in the years between grade school and high school graduation could be learned today in about a dozen weekends. My head start wasn’t really much of a head start.
It’s important to have a “growth mindset” about programming—in other words, understand that people develop programming skills through practice. They aren’t just born as programmers, and being unskilled at programming now is not an indication that you can never become an expert.
Programming Is a Creative Activity
Programming is a creative task, like painting, writing, knitting, or constructing LEGO castles. Like painting a blank canvas, making software has many constraints but endless possibilities.
The difference between programming and other creative activities is that when programming, you have all the raw materials you need in your computer; you don’t need to buy any additional canvas, paint, film, yarn, LEGO bricks, or electronic components. A decade-old computer is more than powerful enough to write programs. Once your program is written, it can be copied perfectly an infinite number of times. A knit sweater can only be worn by one person at a time, but a useful program can easily be shared online with the entire world.
About This Book
The first part of this book covers basic Python programming concepts, and the second part covers various tasks you can have your computer automate. Each chapter in the second part has project programs for you to study. Here’s a brief rundown of what you’ll find in each chapter.
Part I: Python Programming Basics
Chapter 1: Python Basics Covers expressions, the most basic type of Python instruction, and how to use the Python interactive shell software to experiment with code.
Chapter 2: Flow Control Explains how to make programs decide which instructions to execute so your code can intelligently respond to different conditions.
Chapter 3: Functions Instructs you on how to define your own functions so that you can organize your code into more manageable chunks.
Chapter 4: Lists Introduces the list data type and explains how to organize data.
Chapter 5: Dictionaries and Structuring Data Introduces the dictionary data type and shows you more powerful ways to organize data.
Chapter 6: Manipulating Strings Covers working with text data (called strings in Python).
Part II: Automating Tasks
Chapter 7: Pattern Matching with Regular Expressions Covers how Python can manipulate strings and search for text patterns with regular expressions.
Chapter 8: Input Validation Explains how your program can verify the information a user gives it, ensuring that the user’s data arrives in a format that won’t cause errors in the rest of the program. Chapter 9: Reading and Writing Files Explains how your program can read the contents of text files and save information to files on your hard drive.
Chapter 10: Organizing Files Shows how Python can copy, move, rename, and delete large numbers of files much faster than a human user can. Also explains compressing and decompressing files. Chapter 11: Debugging Shows how to use Python’s various bug finding and bug-fixing tools.
Chapter 12: Web Scraping Shows how to write programs that can automatically download web pages and parse them for information. This is called web scraping.
Chapter 13: Working with Excel Spreadsheets Covers programmatically manipulating Excel spreadsheets so that you don’t have to read them. This is helpful when the number of documents you have to analyze is in the hundreds or thousands.
Chapter 14: Working with Google Sheets Covers how to read and update Google Sheets, a popular web-based spreadsheet application, using Python.
Chapter 15: Working with PDF and Word Documents Covers programmatically reading Word and PDF documents. Chapter 16: Working with CSV Files and JSON Data Continues to explain how to programmatically manipulate documents, now discussing CSV and JSON files.
Chapter 17: Keeping Time, Scheduling Tasks, and Launching Programs Explains how Python programs handle time and dates and how to schedule your computer to perform tasks at certain times. Also shows how your Python programs can launch non
Python programs.
Chapter 18: Sending Email and Text Messages Explains how to write programs that can send emails and text messages on your behalf.
Chapter 19: Manipulating Images Explains how to programmatically manipulate images such as JPEG or PNG files. Chapter 20: Controlling the Keyboard and Mouse with GUI Automation Explains how to programmatically control the mouse and keyboard to automate clicks and keypresses.
Appendix A: Installing Third-Party Modules Shows you how to extend Python with useful additional modules.
Appendix B: Running Programs Shows you how to run your Python programs on Windows, macOS, and Linux from outside of the code editor.
Appendix C: Answers to the Practice Questions Provides answers and some additional context to the practice questions at the end of each chapter.
Downloading and Installing Python
You can download Python for Windows, macOS, and Ubuntu for free at https://python.org/downloads/. If you download the latest version from the website’s download page, all of the programs in this book should work.
WARNING
Be sure to download a version of Python 3 (such as 3.8.0). The programs in this book are written to run on Python 3 and may not run correctly, if at
all, on Python 2.
On the download page, you’ll find Python installers for 64-bit and 32-bit computers for each operating system, so first figure out which installer you need. If you bought your computer in 2007 or later, it is most likely a 64-bit system. Otherwise, you have a 32-bit version, but here’s how to find out for sure:
On Windows, select Start ▸ Control Panel ▸ System and check whether System Type says 64-bit or 32-bit.
On macOS, go the Apple menu, select About This Mac ▸ More Info ▸ System Report ▸ Hardware, and then look at the Processor Name field. If it says Intel Core Solo or Intel Core Duo, you have a 32-bit machine. If it says anything else (including Intel Core 2 Duo), you have a 64-bit machine.
On Ubuntu Linux, open a Terminal and run the command uname - m. A response of i686 means 32-bit, and x86_64 means 64-bit.
On Windows, download the Python installer (the filename will end with .msi) and double-click it. Follow the instructions the installer displays on the screen to install Python, as listed here:
1. Select Install for All Users and click Next.
2. Accept the default options for the next several windows by clicking Next.
On macOS, download the .dmg file that’s right for your version of macOS and double-click it. Follow the instructions the installer displays on the screen to install Python, as listed here:
1. When the DMG package opens in a new window, double-click the Python.mpkg file. You may have to enter the administrator password.
2. Accept the default options for the next several windows by clicking Continue and click Agree to accept the license.
3. On the final window, click Install.
If you’re running Ubuntu, you can install Python from the Terminal by following these steps:
1. Open the Terminal window.
2. Enter sudo apt-get install python3.
3. Enter sudo apt-get install idle3.
4. Enter sudo apt-get install python3-pip.
Downloading and Installing Mu
While the Python interpreter is the software that runs your Python programs, the Mu editor software is where you’ll enter your programs, much the way you type in a word processor. You can download Mu from https://codewith.mu/.
On Windows and macOS, download the installer for your operating system and then run it by double-clicking the installer file. If you are on macOS, running the installer opens a window where you must drag the Mu icon to the Applications folder icon to continue the installation. If you are on Ubuntu, you’ll need to install Mu as a Python package. In that case, click the Instructions button in the Python Package section of the download page.
Starting Mu
Once it’s installed, let’s start Mu.
On Windows 7 or later, click the Start icon in the lower-left corner of your screen, enter Mu in the search box, and select it.
On macOS, open the Finder window, click Applications, and then click mu-editor.
On Ubuntu, select Applications ▸ Accessories ▸ Terminal and then enter python3 –m mu.
The first time Mu runs, a Select Mode window will appear with options Adafruit CircuitPython, BBC micro:bit, Pygame Zero, and Python 3. Select Python 3. You can always change the mode later by clicking the Mode button at the top of the editor window.
NOTE
You’ll need to download Mu version 1.10.0 or later in order to install the third-party modules featured in this book. As of this writing, 1.10.0 is an alpha release and is listed on the download page as a separate link from the main download links.
Starting IDLE
This book uses Mu as an editor and interactive shell. However, you can use any number of editors for writing Python code. The Integrated Development and Learning Environment (IDLE) software installs along with Python, and it can serve as a second editor if for some reason you can’t get Mu installed or working. Let’s start IDLE now.
On Windows 7 or later, click the Start icon in the lower-left corner of your screen, enter IDLE in the search box, and select IDLE (Python GUI).
On macOS, open the Finder window, click Applications, click Python 3.8, and then click the IDLE icon.
On Ubuntu, select Applications ▸ Accessories ▸ Terminal and then enter idle3. (You may also be able to click Applications at the top of the screen, select Programming, and then click IDLE 3.)
The Interactive Shell
When you run Mu, the window that appears is called the file editor window. You can open the interactive shell by clicking the REPL button. A shell is a program that lets you type instructions into the computer,
much like the Terminal or Command Prompt on macOS and Windows, respectively. Python’s interactive shell lets you enter instructions for the Python interpreter software to run. The computer reads the instructions you enter and runs them immediately.
In Mu, the interactive shell is a pane in the lower half of the window with the following text:
Jupyter QtConsole 4.3.1
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.
In [1]:
If you run IDLE, the interactive shell is the window that first appears. It should be mostly blank except for text that looks something like this:
Python 3.8.0b1 (tags/v3.8.0b1:3b5deb0116, Jun 4 2019, 19:52:55) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information. >>>
In [1]: and >>> are called prompts. The examples in this book will use the >>> prompt for the interactive shell since it’s more common. If you run Python from the Terminal or Command Prompt, they’ll use the >>> prompt, as well. The In [1]: prompt was invented by Jupyter Notebook, another popular Python editor.
For example, enter the following into the interactive shell next to the prompt:
>>> print('Hello, world!')
After you type that line and press ENTER, the interactive shell should display this in response:
>>> print('Hello, world!')
Hello, world!
You’ve just given the computer an instruction, and it did what you told it to do!
Installing Third-Party Modules
Some Python code requires your program to import modules. Some of these modules come with Python, but others are third-party modules created by developers outside of the Python core dev team. Appendix A has detailed instructions on how to use the pip program (on Windows) or pip3 program (on macOS and Linux) to install third-party modules. Consult Appendix A when this book instructs you to install a particular third-party module.
How to Find Help
Programmers tend to learn by searching the internet for answers to their questions. This is quite different from the way many people are accustomed to learning—through an in-person teacher who lectures and can answer questions. What’s great about using the internet as a schoolroom is that there are whole communities of folks who can answer your questions. Indeed, your questions have probably already been answered, and the answers are waiting online for you to find them. If you encounter an error message or have trouble making your code work, you won’t be the first person to have your problem, and finding a solution is easier than you might think.
For example, let’s cause an error on purpose: enter '42' + 3 into the interactive shell. You don’t need to know what this instruction means right now, but the result should look like this:
>>> '42' + 3
➊ Traceback (most recent call last):
File "", line 1, in
'42' + 3
➋ TypeError: Can't convert 'int' object to str implicitly >>>
The error message ➋ appears because Python couldn’t understand your instruction. The traceback part ➊ of the error message shows the specific instruction and line number that Python had trouble with. If you’re not sure what to make of a particular error message, search for it online. Enter “TypeError: Can’t convert ‘int’ object to str implicitly” (including the quotes) into your favorite search engine, and you should see tons of links explaining what the error message means and what causes it, as shown in Figure 0-2.
Figure 0-2: The Google results for an error message can be very helpful.
You’ll often find that someone else had the same question as you and that some other helpful person has already answered it. No one person can know everything about programming, so an everyday part of any software developer’s job is looking up answers to technical questions.
Asking Smart Programming Questions
If you can’t find the answer by searching online, try asking people in a web forum such as Stack Overflow (https://stackoverflow.com/) or the “learn programming” subreddit at https://reddit.com/r/learnprogramming/. But keep in mind there are smart ways to ask programming questions that help others help you. To begin with, be sure to read the FAQ sections at these websites about the proper way to post questions.
When asking programming questions, remember to do the following:
Explain what you are trying to do, not just what you did. This lets your helper know if you are on the wrong track.
Specify the point at which the error happens. Does it occur at the very start of the program or only after you do a certain action? Copy and paste the entire error message and your code to https://pastebin.com/ or https://gist.github.com/.
These websites make it easy to share large amounts of code with people online, without losing any text formatting. You can then put the URL of the posted code in your email or forum post. For example, here some pieces of code I’ve posted: https://pastebin.com/SzP2DbFx/ and https://gist.github.com/asweigart/6912168/.
Explain what you’ve already tried to do to solve your problem. This tells people you’ve already put in some work to figure things out on your own.
List the version of Python you’re using. (There are some key differences between version 2 Python interpreters and version 3 Python interpreters.) Also, say which operating system and version you’re running.
If the error came up after you made a change to your code, explain exactly what you changed.
Say whether you’re able to reproduce the error every time you run the program or whether it happens only after you perform certain
actions. If the latter, then explain what those actions are.
Always follow good online etiquette as well. For example, don’t post your questions in all caps or make unreasonable demands of the people trying to help you.
You can find more information on how to ask for programming help in the blog post at https://autbor.com/help/. You can find a list of frequently asked questions about programming at https://www.reddit.com/r/learnprogramming/wiki/faq/ and a similar list about getting a job in software development at https://www.reddit.com/r/cscareerquestions/wiki/index/.
I love helping people discover Python. I write programming tutorials on my blog at https://inventwithpython.com/blog/, and you can contact me with questions at [email protected]. Although, you may get a faster response by posting your questions to https://reddit.com/r/inventwithpython/.
Summary
For most people, their computer is just an appliance instead of a tool. But by learning how to program, you’ll gain access to one of the most powerful tools of the modern world, and you’ll have fun along the way. Programming isn’t brain surgery—it’s fine for amateurs to experiment and make mistakes.
This book assumes you have zero programming knowledge and will teach you quite a bit, but you may have questions beyond its scope. Remember that asking effective questions and knowing how to find answers are invaluable tools on your programming journey.
Let’s begin!
PART I
PYTHON PROGRAMMING BASICS
1
PYTHON BASICS
The Python programming language has a wide range of syntactical constructions, standard library functions, and interactive development environment features. Fortunately, you can ignore most of that; you just need to learn enough to write some handy little programs.
You will, however, have to learn some basic programming concepts before you can do anything. Like a wizard in training, you might think these concepts seem arcane and tedious, but with some knowledge and practice, you’ll be able to command your computer like a magic wand and perform incredible feats.
This chapter has a few examples that encourage you to type into the interactive shell, also called the REPL (Read-Evaluate-Print Loop), which lets you run (or execute) Python instructions one at a time and instantly shows you the results. Using the interactive shell is great for learning what basic Python instructions do, so give it a try as you follow along. You’ll remember the things you do much better than the things you only read.
Entering Expressions into the Interactive Shell
You can run the interactive shell by launching the Mu editor, which you should have downloaded when going through the setup instructions in the Preface. On Windows, open the Start menu, type “Mu,” and open the Mu app. On macOS, open your Applications folder and double
click Mu. Click the New button and save an empty file as blank.py. When you run this blank file by clicking the Run button or pressing F5, it will open the interactive shell, which will open as a new pane that opens at the bottom of the Mu editor’s window. You should see a >>> prompt in the interactive shell.
Enter 2 + 2 at the prompt to have Python do some simple math. The Mu window should now look like this:
>>> 2 + 2
4
>>>
In Python, 2 + 2 is called an expression, which is the most basic kind of programming instruction in the language. Expressions consist of values (such as 2) and operators (such as +), and they can always evaluate (that is, reduce) down to a single value. That means you can use expressions anywhere in Python code that you could also use a value.
In the previous example, 2 + 2 is evaluated down to a single value, 4. A single value with no operators is also considered an expression, though it evaluates only to itself, as shown here:
>>> 2
2
ERRORS ARE OKAY!
Programs will crash if they contain code the computer can’t understand, which will cause Python to show an error message. An error message won’t break your computer, though, so don’t be afraid to make mistakes. A crash just means the program stopped running unexpectedly.
If you want to know more about an error, you can search for the exact error message text online for more information. You can also check out the resources at https://nostarch.com/automatestuf 2/ to see a list of common Python error messages and their meanings.
You can use plenty of other operators in Python expressions, too. For example, Table 1-1 lists all the math operators in Python.
Table 1-1: Math Operators from Highest to Lowest Precedence
Operator Operation Example Evaluates to . . .
** Exponent 2 ** 3 8 % Modulus/remainder 22 % 8 6
// Integer
division/floored
quotient
22 // 8 2
/ Division 22 / 8 2.75 * Multiplication 3 * 5 15 - Subtraction 5 - 2 3 + Addition 2 + 2 4
The order of operations (also called precedence) of Python math operators is similar to that of mathematics. The ** operator is evaluated first; the *, /, //, and % operators are evaluated next, from left to right; and the + and - operators are evaluated last (also from left to right). You can use parentheses to override the usual precedence if you need to. Whitespace in between the operators and values doesn’t matter for Python (except for the indentation at the beginning of the line), but a single space is convention. Enter the following expressions into the interactive shell:
>>> 2 + 3 * 6
20
>>> (2 + 3) * 6
30
>>> 48565878 * 578453
28093077826734
>>> 2 ** 8
256
>>> 23 / 7
3.2857142857142856
>>> 23 // 7
3
>>> 23 % 7
2
>>> 2 + 2
4
>>> (5 - 1) * ((7 + 1) / (3 - 1))
16.0
In each case, you as the programmer must enter the expression, but Python does the hard part of evaluating it down to a single value. Python will keep evaluating parts of the expression until it becomes a single value, as shown here:
These rules for putting operators and values together to form expressions are a fundamental part of Python as a programming language, just like the grammar rules that help us communicate. Here’s an example:
This is a grammatically correct English sentence.
This grammatically is sentence not English correct a.
The second line is difficult to parse because it doesn’t follow the rules of English. Similarly, if you enter a bad Python instruction, Python won’t be able to understand it and will display a SyntaxError error message, as shown here:
>>> 5 +
File "", line 1
5 +
^
SyntaxError: invalid syntax
>>> 42 + 5 + * 2
File "", line 1
42 + 5 + * 2
^
SyntaxError: invalid syntax
You can always test to see whether an instruction works by entering it into the interactive shell. Don’t worry about breaking the computer: the worst that could happen is that Python responds with an error message. Professional software developers get error messages while writing code all the time.
The Integer, Floating-Point, and String Data Types
Remember that expressions are just values combined with operators, and they always evaluate down to a single value. A data type is a category for values, and every value belongs to exactly one data type. The most common data types in Python are listed in Table 1-2. The values -2 and 30, for example, are said to be integer values. The integer (or int) data type indicates values that are whole numbers. Numbers with a decimal point, such as 3.14, are called floating-point numbers (or floats). Note that even though the value 42 is an integer, the value 42.0 would be a floating point number.
Table 1-2: Common Data Types
Data type Examples
Integers -2, -1, 0, 1, 2, 3, 4, 5
Floating-point numbers -1.25, -1.0, -0.5, 0.0, 0.5, 1.0, 1.25 Strings 'a', 'aa', 'aaa', 'Hello!', '11 cats'
Python programs can also have text values called strings, or strs (pronounced “stirs”). Always surround your string in single quote (') characters (as in 'Hello' or 'Goodbye cruel world!') so Python knows where the string begins and ends. You can even have a string with no characters in it, '', called a blank string or an empty string. Strings are explained in greater detail in Chapter 4.
If you ever see the error message SyntaxError: EOL while scanning string literal, you probably forgot the final single quote character at the end of the string, such as in this example:
>>> 'Hello, world!
SyntaxError: EOL while scanning string literal
String Concatenation and Replication
The meaning of an operator may change based on the data types of the values next to it. For example, + is the addition operator when it operates on two integers or floating-point values. However, when + is used on two string values, it joins the strings as the string concatenation operator. Enter the following into the interactive shell:
>>> 'Alice' + 'Bob'
'AliceBob'
The expression evaluates down to a single, new string value that combines the text of the two strings. However, if you try to use the + operator on a string and an integer value, Python will not know how to handle this, and it will display an error message.
>>> 'Alice' + 42
Traceback (most recent call last):
File "", line 1, in
'Alice' + 42
TypeError: can only concatenate str (not "int") to str
The error message can only concatenate str (not "int") to str means that Python thought you were trying to concatenate an integer to the string 'Alice'. Your code will have to explicitly convert the integer to a
string because Python cannot do this automatically. (Converting data types will be explained in “Dissecting Your Program” on page 13 when we talk about the str(), int(), and float() functions.)
The * operator multiplies two integer or floating-point values. But when the * operator is used on one string value and one integer value, it becomes the string replication operator. Enter a string multiplied by a number into the interactive shell to see this in action.
>>> 'Alice' * 5
'AliceAliceAliceAliceAlice'
The expression evaluates down to a single string value that repeats the original string a number of times equal to the integer value. String replication is a useful trick, but it’s not used as often as string concatenation.
The * operator can be used with only two numeric values (for multiplication), or one string value and one integer value (for string replication). Otherwise, Python will just display an error message, like the following:
>>> 'Alice' * 'Bob'
Traceback (most recent call last):
File "", line 1, in
'Alice' * 'Bob'
TypeError: can't multiply sequence by non-int of type 'str' >>> 'Alice' * 5.0
Traceback (most recent call last):
File "", line 1, in
'Alice' * 5.0
TypeError: can't multiply sequence by non-int of type 'float'
It makes sense that Python wouldn’t understand these expressions: you can’t multiply two words, and it’s hard to replicate an arbitrary string a fractional number of times.
Storing Values in Variables
A variable is like a box in the computer’s memory where you can store a single value. If you want to use the result of an evaluated expression
later in your program, you can save it inside a variable.
Assignment Statements
You’ll store values in variables with an assignment statement. An assignment statement consists of a variable name, an equal sign (called the assignment operator), and the value to be stored. If you enter the assignment statement spam = 42, then a variable named spam will have the integer value 42 stored in it.
Think of a variable as a labeled box that a value is placed in, as in Figure 1-1.
Figure 1-1: spam = 42 is like telling the program, “The variable spam now has the integer value 42 in it.”
For example, enter the following into the interactive shell:
➊ >>> spam = 40
>>> spam
40
>>> eggs = 2
➋ >>> spam + eggs
42
>>> spam + eggs + spam
82
➌ >>> spam = spam + 2
>>> spam
42
A variable is initialized (or created) the first time a value is stored in it ➊. After that, you can use it in expressions with other variables and values ➋. When a variable is assigned a new value ➌, the old value is forgotten, which is why spam evaluated to 42 instead of 40 at the end of the example. This is called overwriting the variable. Enter the following code into the interactive shell to try overwriting a string:
>>> spam = 'Hello'
>>> spam
'Hello'
>>> spam = 'Goodbye'
>>> spam
'Goodbye'
Just like the box in Figure 1-2, the spam variable in this example stores 'Hello' until you replace the string with 'Goodbye'.
Figure 1-2: When a new value is assigned to a variable, the old one is forgotten.
Variable Names
A good variable name describes the data it contains. Imagine that you moved to a new house and labeled all of your moving boxes as Stuf . You’d never find anything! Most of this book’s examples (and Python’s documentation) use generic variable names like spam, eggs, and bacon, which come from the Monty Python “Spam” sketch. But in your programs, a descriptive name will help make your code more readable.
Though you can name your variables almost anything, Python does have some naming restrictions. Table 1-3 has examples of legal variable names. You can name a variable anything as long as it obeys the following three rules:
It can be only one word with no spaces.
It can use only letters, numbers, and the underscore (_) character. It can’t begin with a number.
Table 1-3: Valid and Invalid Variable Names
Valid variable names Invalid variable names
current_balance current-balance (hyphens are not allowed)
currentBalance current balance (spaces are not allowed)
account4 4account (can’t begin with a number) _42 42 (can’t begin with a number)
TOTAL_SUM TOTAL_$UM (special characters like $ are not allowed)
hello 'hello' (special characters like ' are not allowed)
Variable names are case-sensitive, meaning that spam, SPAM, Spam, and sPaM are four different variables. Though Spam is a valid variable you can use in a program, it is a Python convention to start your variables with a lowercase letter.
This book uses camelcase for variable names instead of underscores; that is, variables lookLikeThis instead of looking_like_this. Some experienced programmers may point out that the official Python code style, PEP 8, says that underscores should be used. I unapologetically prefer camelcase and point to the “A Foolish Consistency Is the Hobgoblin of Little Minds” section in PEP 8 itself:
Consistency with the style guide is important. But most importantly: know when to be inconsistent—sometimes the style guide just doesn’t apply. When in doubt, use your best judgment.
Your First Program
While the interactive shell is good for running Python instructions one at a time, to write entire Python programs, you’ll type the instructions into the file editor. The file editor is similar to text editors such as Notepad or TextMate, but it has some features specifically for entering source code. To open a new file in Mu, click the New button on the top row.
The window that appears should contain a cursor awaiting your input, but it’s different from the interactive shell, which runs Python instructions as soon as you press ENTER. The file editor lets you type in many instructions, save the file, and run the program. Here’s how you can tell the difference between the two:
The interactive shell window will always be the one with the >>> prompt.
The file editor window will not have the >>> prompt.
Now it’s time to create your first program! When the file editor window opens, enter the following into it:
➊ # This program says hello and asks for my name.
➋ print('Hello, world!')
print('What is your name?') # ask for their name
➌ myName = input()
➍ print('It is good to meet you, ' + myName)
➎ print('The length of your name is:')
print(len(myName))
➏ print('What is your age?') # ask for their age
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
Once you’ve entered your source code, save it so that you won’t have to retype it each time you start Mu. Click the Save button, enter hello.py in the File Name field, and then click Save.
You should save your programs every once in a while as you type them. That way, if the computer crashes or you accidentally exit Mu,
you won’t lose the code. As a shortcut, you can press CTRL-S on Windows and Linux or -S on macOS to save your file. Once you’ve saved, let’s run our program. Press the F5 key. Your program should run in the interactive shell window. Remember, you have to press F5 from the file editor window, not the interactive shell window. Enter your name when your program asks for it. The program’s output in the interactive shell should look something like this:
Python 3.7.0b4 (v3.7.0b4:eb96c37699, May 2 2018, 19:02:22) [MSC v.1913 64 bit
(AMD64)] on win32
Type "copyright", "credits" or "license()" for more information. >>> ================================ RESTART
================================
>>>
Hello, world!
What is your name?
Al
It is good to meet you, Al
The length of your name is:
2
What is your age?
4
You will be 5 in a year.
>>>
When there are no more lines of code to execute, the Python program terminates; that is, it stops running. (You can also say that the Python program exits.)
You can close the file editor by clicking the X at the top of the window. To reload a saved program, select File▸Open... from the menu. Do that now, and in the window that appears, choose hello.py and click the Open button. Your previously saved hello.py program should open in the file editor window.
You can view the execution of a program using the Python Tutor visualization tool at http://pythontutor.com/. You can see the execution of this particular program at https://autbor.com/hellopy/. Click the forward button to move through each step of the program’s execution. You’ll be able to see how the variables’ values and the output change.
Dissecting Your Program
With your new program open in the file editor, let’s take a quick tour of the Python instructions it uses by looking at what each line of code does.
Comments
The following line is called a comment.
➊ # This program says hello and asks for my name.
Python ignores comments, and you can use them to write notes or remind yourself what the code is trying to do. Any text for the rest of the line following a hash mark (#) is part of a comment.
Sometimes, programmers will put a # in front of a line of code to temporarily remove it while testing a program. This is called commenting out code, and it can be useful when you’re trying to figure out why a program isn’t working. You can remove the # later when you are ready to put the line back in.
Python also ignores the blank line after the comment. You can add as many blank lines to your program as you want. This can make your code easier to read, like paragraphs in a book.
The print() Function
The print() function displays the string value inside its parentheses on the screen.
➋ print('Hello, world!')
print('What is your name?') # ask for their name
The line print('Hello, world!') means “Print out the text in the string 'Hello, world!'.” When Python executes this line, you say that Python is calling the print() function and the string value is being passed to the function. A value that is passed to a function call is an argument. Notice
that the quotes are not printed to the screen. They just mark where the string begins and ends; they are not part of the string value.
NOTE
You can also use this function to put a blank line on the screen; just call print() with nothing in between the parentheses.
When you write a function name, the opening and closing parentheses at the end identify it as the name of a function. This is why in this book, you’ll see print() rather than print. Chapter 3 describes functions in more detail.
The input() Function
The input() function waits for the user to type some text on the keyboard and press ENTER.
➌ myName = input()
This function call evaluates to a string equal to the user’s text, and the line of code assigns the myName variable to this string value. You can think of the input() function call as an expression that evaluates to whatever string the user typed in. If the user entered 'Al', then the expression would evaluate to myName = 'Al'.
If you call input() and see an error message, like NameError: name 'Al' is not defined, the problem is that you’re running the code with Python 2 instead of Python 3.
Printing the User’s Name
The following call to print() actually contains the expression 'It is good to meet you, ' + myName between the parentheses.
➍ print('It is good to meet you, ' + myName)
Remember that expressions can always evaluate to a single value. If 'Al' is the value stored in myName on line ➌, then this expression evaluates to 'It is good to meet you, Al'. This single string value is then passed to print(), which prints it on the screen.
The len() Function
You can pass the len() function a string value (or a variable containing a string), and the function evaluates to the integer value of the number of characters in that string.
➎ print('The length of your name is:')
print(len(myName))
Enter the following into the interactive shell to try this:
>>> len('hello')
5
>>> len('My very energetic monster just scarfed nachos.')
46
>>> len('')
0
Just like those examples, len(myName) evaluates to an integer. It is then passed to print() to be displayed on the screen. The print() function allows you to pass it either integer values or string values, but notice the error that shows up when you type the following into the interactive shell:
>>> print('I am ' + 29 + ' years old.')
Traceback (most recent call last):
File "", line 1, in
print('I am ' + 29 + ' years old.')
TypeError: can only concatenate str (not "int") to str
The print() function isn’t causing that error, but rather it’s the expression you tried to pass to print(). You get the same error message if you type the expression into the interactive shell on its own.
>>> 'I am ' + 29 + ' years old.'
Traceback (most recent call last):
File "", line 1, in
'I am ' + 29 + ' years old.'
TypeError: can only concatenate str (not "int") to str
Python gives an error because the + operator can only be used to add two integers together or concatenate two strings. You can’t add an integer to a string, because this is ungrammatical in Python. You can fix this by using a string version of the integer instead, as explained in the next section.
The str(), int(), and float() Functions
If you want to concatenate an integer such as 29 with a string to pass to print(), you’ll need to get the value '29', which is the string form of 29. The str() function can be passed an integer value and will evaluate to a string value version of the integer, as follows:
>>> str(29)
'29'
>>> print('I am ' + str(29) + ' years old.')
I am 29 years old.
Because str(29) evaluates to '29', the expression 'I am ' + str(29) + ' years old.' evaluates to 'I am ' + '29' + ' years old.', which in turn evaluates to 'I am 29 years old.'. This is the value that is passed to the print() function.
The str(), int(), and float() functions will evaluate to the string, integer, and floating-point forms of the value you pass, respectively. Try converting some values in the interactive shell with these functions and watch what happens.
>>> str(0)
'0'
>>> str(-3.14)
'-3.14'
>>> int('42')
42
>>> int('-99')
-99
>>> int(1.25)
1
>>> int(1.99)
1
>>> float('3.14')
3.14
>>> float(10)
10.0
The previous examples call the str(), int(), and float() functions and pass them values of the other data types to obtain a string, integer, or floating-point form of those values.
The str() function is handy when you have an integer or float that you want to concatenate to a string. The int() function is also helpful if you have a number as a string value that you want to use in some mathematics. For example, the input() function always returns a string, even if the user enters a number. Enter spam = input() into the interactive shell and enter 101 when it waits for your text.
>>> spam = input()
101
>>> spam
'101'
The value stored inside spam isn’t the integer 101 but the string '101'. If you want to do math using the value in spam, use the int() function to get the integer form of spam and then store this as the new value in spam.
>>> spam = int(spam)
>>> spam
101
Now you should be able to treat the spam variable as an integer instead of a string.
>>> spam * 10 / 5
202.0
Note that if you pass a value to int() that it cannot evaluate as an integer, Python will display an error message.
>>> int('99.99')
Traceback (most recent call last):
File "", line 1, in
int('99.99')
ValueError: invalid literal for int() with base 10: '99.99' >>> int('twelve')
Traceback (most recent call last):
File "", line 1, in
int('twelve')
ValueError: invalid literal for int() with base 10: 'twelve'
The int() function is also useful if you need to round a floating-point number down.
>>> int(7.7)
7
>>> int(7.7) + 1
8
You used the int() and str() functions in the last three lines of your program to get a value of the appropriate data type for the code.
➏ print('What is your age?') # ask for their age
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
TEXT AND NUMBER EQUIVALENCE
Although the string value of a number is considered a completely different value from the integer or floating-point version, an integer can be equal to a floating point.
>>> 42 == '42'
False
>>> 42 == 42.0
True
>>> 42.0 == 0042.000
True
Python makes this distinction because strings are text, while integers and floats are both numbers.
The myAge variable contains the value returned from input(). Because the input() function always returns a string (even if the user typed in a number), you can use the int(myAge) code to return an integer value of
the string in myAge. This integer value is then added to 1 in the expression int(myAge) + 1.
The result of this addition is passed to the str() function: str(int(myAge) + 1). The string value returned is then concatenated with the strings 'You will be ' and ' in a year.' to evaluate to one large string value. This large string is finally passed to print() to be displayed on the screen.
Let’s say the user enters the string '4' for myAge. The string '4' is converted to an integer, so you can add one to it. The result is 5. The str() function converts the result back to a string, so you can concatenate it with the second string, 'in a year.', to create the final message. These evaluation steps would look something like the following:
Summary
You can compute expressions with a calculator or enter string concatenations with a word processor. You can even do string replication easily by copying and pasting text. But expressions, and their component values—operators, variables, and function calls—are the basic building blocks that make programs. Once you know how to
handle these elements, you will be able to instruct Python to operate on large amounts of data for you.
It is good to remember the different types of operators (+, -, *, /, //, %, and ** for math operations, and + and * for string operations) and the three data types (integers, floating-point numbers, and strings) introduced in this chapter.
I introduced a few different functions as well. The print() and input() functions handle simple text output (to the screen) and input (from the keyboard). The len() function takes a string and evaluates to an int of the number of characters in the string. The str(), int(), and float() functions will evaluate to the string, integer, or floating-point number form of the value they are passed.
In the next chapter, you’ll learn how to tell Python to make intelligent decisions about what code to run, what code to skip, and what code to repeat based on the values it has. This is known as flow control, and it allows you to write programs that make intelligent decisions.
Practice Questions
1. Which of the following are operators, and which are values?
*
'hello'
-88.8
-
/
+
5
2. Which of the following is a variable, and which is a string?
spam
'spam'
3. Name three data types.
4. What is an expression made up of? What do all expressions do?
5. This chapter introduced assignment statements, like spam = 10. What is the difference between an expression and a statement?
6. What does the variable bacon contain after the following code runs?
bacon = 20
bacon + 1
7. What should the following two expressions evaluate to?
'spam' + 'spamspam'
'spam' * 3
8. Why is eggs a valid variable name while 100 is invalid?
9. What three functions can be used to get the integer, floating-point number, or string version of a value?
10. Why does this expression cause an error? How can you fix it?
'I have eaten ' + 99 + ' burritos.'
Extra credit: Search online for the Python documentation for the len() function. It will be on a web page titled “Built-in Functions.” Skim the list of other functions Python has, look up what the round() function does, and experiment with it in the interactive shell.
2
FLOW CONTROL
So, you know the basics of individual instructions and that a program is just a series of instructions. But programming’s real strength isn’t just running one instruction after another like a weekend errand list. Based on how expressions evaluate, a program can decide to skip instructions, repeat them, or choose one of several instructions to run. In fact, you almost never want your programs to start from the first line of code and simply execute every line, straight to the end. Flow control statements can decide which Python instructions to execute under which conditions.
These flow control statements directly correspond to the symbols in a flowchart, so I’ll provide flowchart versions of the code discussed in this chapter. Figure 2-1 shows a flowchart for what to do if it’s raining. Follow the path made by the arrows from Start to End.
Figure 2-1: A flowchart to tell you what to do if it is raining
In a flowchart, there is usually more than one way to go from the start to the end. The same is true for lines of code in a computer program. Flowcharts represent these branching points with diamonds, while the other steps are represented with rectangles. The starting and ending steps are represented with rounded rectangles.
But before you learn about flow control statements, you first need to learn how to represent those yes and no options, and you need to understand how to write those branching points as Python code. To that end, let’s explore Boolean values, comparison operators, and Boolean operators.
Boolean Values
While the integer, floating-point, and string data types have an unlimited number of possible values, the Boolean data type has only two values: True and False. (Boolean is capitalized because the data type is named after mathematician George Boole.) When entered as Python code, the Boolean values True and False lack the quotes you place around strings, and they always start with a capital T or F, with the rest of the word in lowercase. Enter the following into the interactive shell. (Some of these instructions are intentionally incorrect, and they’ll cause error messages to appear.)
➊ >>> spam = True
>>> spam
True
➋ >>> true
Traceback (most recent call last):
File "", line 1, in
true
NameError: name 'true' is not defined
➌ >>> True = 2 + 2
SyntaxError: can't assign to keyword
Like any other value, Boolean values are used in expressions and can be stored in variables ➊. If you don’t use the proper case ➋ or you try to use True and False for variable names ➌, Python will give you an error message.
Comparison Operators
Comparison operators, also called relational operators, compare two values and evaluate down to a single Boolean value. Table 2-1 lists the comparison operators.
Table 2-1: Comparison Operators
Operator Meaning
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
These operators evaluate to True or False depending on the values you give them. Let’s try some operators now, starting with == and !=.
>>> 42 == 42
True
>>> 42 == 99
False
>>> 2 != 3
True
>>> 2 != 2
False
As you might expect, == (equal to) evaluates to True when the values on both sides are the same, and != (not equal to) evaluates to True when the two values are different. The == and != operators can actually work with values of any data type.
>>> 'hello' == 'hello'
True
>>> 'hello' == 'Hello'
False
>>> 'dog' != 'cat'
True
>>> True == True
True
>>> True != False
True
>>> 42 == 42.0
True
➊ >>> 42 == '42'
False
Note that an integer or floating-point value will always be unequal to a string value. The expression 42 == '42' ➊ evaluates to False because Python considers the integer 42 to be different from the string '42'. The <, >, <=, and >= operators, on the other hand, work properly only with integer and floating-point values.
>>> 42 < 100
True
>>> 42 > 100
False
>>> 42 < 42
False
>>> eggCount = 42
➊ >>> eggCount <= 42
True
>>> myAge = 29
➋ >>> myAge >= 10
True
THE DIFFERENCE BETWEEN THE == AND = OPERATORS
You might have noticed that the == operator (equal to) has two equal signs, while the = operator (assignment) has just one equal sign. It’s easy to confuse these two operators with each other. Just remember these points:
The == operator (equal to) asks whether two values are the same as each other.
The = operator (assignment) puts the value on the right into the variable on the left.
To help remember which is which, notice that the == operator (equal to) consists of two characters, just like the != operator (not equal to) consists of two characters.
You’ll often use comparison operators to compare a variable’s value to some other value, like in the eggCount <= 42 ➊ and myAge >= 10 ➋ examples. (After all, instead of entering 'dog' != 'cat' in your code, you could have just entered True.) You’ll see more examples of this later when you learn about flow control statements.
Boolean Operators
The three Boolean operators (and, or, and not) are used to compare Boolean values. Like comparison operators, they evaluate these expressions down to a Boolean value. Let’s explore these operators in detail, starting with the and operator.
Binary Boolean Operators
The and and or operators always take two Boolean values (or expressions), so they’re considered binary operators. The and operator evaluates an expression to True if both Boolean values are True; otherwise, it evaluates to False. Enter some expressions using and into the interactive shell to see it in action.
>>> True and True
True
>>> True and False
False
A truth table shows every possible result of a Boolean operator. Table 2-2 is the truth table for the and operator.
Table 2-2: The and Operator’s Truth Table
Expression Evaluates to . . .
True and True True
True and False False
False and True False
False and False False
On the other hand, the or operator evaluates an expression to True if either of the two Boolean values is True. If both are False, it evaluates to False.
>>> False or True
True
>>> False or False
False
You can see every possible outcome of the or operator in its truth table, shown in Table 2-3. Table 2-3: The or Operator’s Truth Table
Expression Evaluates to . . .
True or True True
True or False True
False or True True
False or False False
The not Operator
Unlike and and or, the not operator operates on only one Boolean value (or expression). This makes it a unary operator. The not operator simply evaluates to the opposite Boolean value.
>>> not True
False
➊ >>> not not not not True
True
Much like using double negatives in speech and writing, you can nest not operators ➊, though there’s never not no reason to do this in real programs. Table 2-4 shows the truth table for not.
Table 2-4: The not Operator’s Truth Table
Expression Evaluates to . . .
Expression Evaluates to . . .
not True False
not False True
Mixing Boolean and Comparison Operators
Since the comparison operators evaluate to Boolean values, you can use them in expressions with the Boolean operators.
Recall that the and, or, and not operators are called Boolean operators because they always operate on the Boolean values True and False. While expressions like 4 < 5 aren’t Boolean values, they are expressions that evaluate down to Boolean values. Try entering some Boolean expressions that use comparison operators into the interactive shell.
>>> (4 < 5) and (5 < 6)
True
>>> (4 < 5) and (9 < 6)
False
>>> (1 == 2) or (2 == 2)
True
The computer will evaluate the left expression first, and then it will evaluate the right expression. When it knows the Boolean value for each, it will then evaluate the whole expression down to one Boolean value. You can think of the computer’s evaluation process for (4 < 5) and (5 < 6) as the following:
You can also use multiple Boolean operators in an expression, along with the comparison operators:
>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2
True
The Boolean operators have an order of operations just like the math operators do. After any math and comparison operators evaluate, Python evaluates the not operators first, then the and operators, and then the or operators.
Elements of Flow Control
Flow control statements often start with a part called the condition and are always followed by a block of code called the clause. Before you learn about Python’s specific flow control statements, I’ll cover what a condition and a block are.
Conditions
The Boolean expressions you’ve seen so far could all be considered conditions, which are the same thing as expressions; condition is just a more specific name in the context of flow control statements. Conditions always evaluate down to a Boolean value, True or False. A flow control statement decides what to do based on whether its condition is True or False, and almost every flow control statement uses a condition.
Blocks of Code
Lines of Python code can be grouped together in blocks. You can tell when a block begins and ends from the indentation of the lines of code. There are three rules for blocks.
Blocks begin when the indentation increases.
Blocks can contain other blocks.
Blocks end when the indentation decreases to zero or to a containing block’s indentation.
Blocks are easier to understand by looking at some indented code, so let’s find the blocks in part of a small game program, shown here:
name = 'Mary'
password = 'swordfish'
if name == 'Mary':
➊ print('Hello, Mary')
if password == 'swordfish':
➋ print('Access granted.')
else:
➌ print('Wrong password.')
You can view the execution of this program at https://autbor.com/blocks/. The first block of code ➊ starts at the line print('Hello, Mary') and contains all the lines after it. Inside this block is another block ➋, which has only a single line in it: print('Access Granted.'). The third block ➌ is also one line long: print('Wrong password.').
Program Execution
In the previous chapter’s hello.py program, Python started executing instructions at the top of the program going down, one after another. The program execution (or simply, execution) is a term for the current instruction being executed. If you print the source code on paper and put your finger on each line as it is executed, you can think of your finger as the program execution.
Not all programs execute by simply going straight down, however. If you use your finger to trace through a program with flow control statements, you’ll likely find yourself jumping around the source code based on conditions, and you’ll probably skip entire clauses.
Flow Control Statements
Now, let’s explore the most important piece of flow control: the statements themselves. The statements represent the diamonds you saw in the flowchart in Figure 2-1, and they are the actual decisions your programs will make.
if Statements
The most common type of flow control statement is the if statement. An if statement’s clause (that is, the block following the if statement) will execute if the statement’s condition is True. The clause is skipped if the condition is False.
In plain English, an if statement could be read as, “If this condition is true, execute the code in the clause.” In Python, an if statement consists of the following:
The if keyword
A condition (that is, an expression that evaluates to True or False)
A colon
Starting on the next line, an indented block of code (called the if clause)
For example, let’s say you have some code that checks to see whether someone’s name is Alice. (Pretend name was assigned some value earlier.)
if name == 'Alice':
print('Hi, Alice.')
All flow control statements end with a colon and are followed by a new block of code (the clause). This if statement’s clause is the block with print('Hi, Alice.'). Figure 2-2 shows what a flowchart of this code would look like.
Figure 2-2: The flowchart for an if statement
else Statements
An if clause can optionally be followed by an else statement. The else clause is executed only when the if statement’s condition is False. In plain English, an else statement could be read as, “If this condition is true, execute this code. Or else, execute that code.” An else statement doesn’t have a condition, and in code, an else statement always consists of the following:
The else keyword
A colon
Starting on the next line, an indented block of code (called the else clause)
Returning to the Alice example, let’s look at some code that uses an else statement to offer a different greeting if the person’s name isn’t Alice.
if name == 'Alice':
print('Hi, Alice.')
else:
print('Hello, stranger.')
Figure 2-3 shows what a flowchart of this code would look like.
Figure 2-3: The flowchart for an else statement
elif Statements
While only one of the if or else clauses will execute, you may have a case where you want one of many possible clauses to execute. The elif statement is an “else if” statement that always follows an if or another elif statement. It provides another condition that is checked only if all of the previous conditions were False. In code, an elif statement always consists of the following:
The elif keyword
A condition (that is, an expression that evaluates to True or False)
A colon
Starting on the next line, an indented block of code (called the elif clause)
Let’s add an elif to the name checker to see this statement in action.
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
This time, you check the person’s age, and the program will tell them something different if they’re younger than 12. You can see the flowchart for this in Figure 2-4.
Figure 2-4: The flowchart for an elif statement
The elif clause executes if age < 12 is True and name == 'Alice' is False. However, if both of the conditions are False, then both of the clauses are skipped. It is not guaranteed that at least one of the clauses will be executed. When there is a chain of elif statements, only one or none of the clauses will be executed. Once one of the statements’ conditions is found to be True, the rest of the elif clauses are automatically skipped. For example, open a new file editor window and enter the following code, saving it as vampire.py:
name = 'Carol'
age = 3000
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif age > 100:
print('You are not Alice, grannie.')
You can view the execution of this program at https://autbor.com/vampire/. Here, I’ve added two more elif statements to make the name checker greet a person with different answers based on age. Figure 2-5 shows the flowchart for this.