Python Cheat Sheet
Python Cheat Sheet
Basic cheatsheet for Python mostly based on the book written by Al Sweigart, Automate the Boring Stuff with
Python under the Creative Commons license and many other sources.
Read It
Online
Github
PDF
Python Cheatsheet
Python Basics
Math Operators
Data Types
String Concatenation and Replication
Variables
Comments
The print() Function
The input() Function
The len() Function
The str(), int(), and float() Functions
Flow Control
Comparison Operators
Boolean Operators
Mixing Boolean and Comparison Operators
if Statements
else Statements
elif Statements
while Loop Statements
break Statements
continue Statements
for Loops and the range() Function
Importing Modules
Ending a Program Early with sys.exit()
Functions
Return Values and return Statements
The None Value
Keyword Arguments and print()
Local and Global Scope
The global Statement
Exception Handling
Lists
1/59
Getting Individual Values in a List with Indexes
Negative Indexes
Getting Sublists with Slices
Getting a List’s Length with len()
Changing Values in a List with Indexes
List Concatenation and List Replication
Removing Values from Lists with del Statements
Using for Loops with Lists
The in and not in Operators
The Multiple Assignment Trick
Augmented Assignment Operators
Finding a Value in a List with the index() Method
Adding Values to Lists with the append() and insert() Mthods
Removing Values from Lists with remove()
Sorting the Values in a List with the sort() Method
Tuple Data Type
Converting Types with the list() and tuple() Functions
Dictionaries and Structuring Data
The keys(), values(), and items() Methods
Checking Whether a Key or Value Exists in a Dictionary
The get() Method
The setdefault() Method
Pretty Printing
Manipulating Strings
Escape Characters
Raw Strings
Multiline Strings with Triple Quotes
Indexing and Slicing Strings
The in and not in Operators with Strings
The upper(), lower(), isupper(), and islower() String Mthods
The isX String Methods
The startswith() and endswith() String Methods
The join() and split() String Methods
Justifying Text with rjust(), ljust(), and center()
Removing Whitespace with strip(), rstrip(), and lstrip()
Copying and Pasting Strings with the pyperclip Module
Regular Expressions
Matching Regex Objects
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 Curly Brackets
Greedy and Nongreedy Matching
2/59
The findall() Method
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
Reading and Writing Files
Backslash on Windows and Forward Slash on OS X and Linux
The Current Working Directory
Absolute vs. Relative Paths
Creating New Folders with os.makedirs()
Handling Absolute and Relative Paths
Finding File Sizes and Folder Contents
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
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
Reading ZIP Files
Extracting from ZIP Files
Creating and Adding to ZIP Files
Debugging
Raising Exceptions
Getting the Traceback as a String
Assertions
Logging
Logging Levels
Disabling Logging
Logging to a File
Virtual Environment
Windows
Lambda Functions
Ternary Conditional Operator
3/59
Python Basics
Math Operators
** Exponent 2 ** 3 = 8
% Modulus/Remaider 22 % 8 = 6
// Integer division 22 // 8 = 2
/ Division 22 / 8 = 2.75
* Multiplication 3*3=9
- Subtraction 5-2=3
+ Addition 2+2=4
>>> 2 + 3 * 6
20
>>> (2 + 3) * 6
30
>>> 2 ** 8
256
>>> 23 // 7
3
>>> 23 % 7
2
Data Types
4/59
Strings 'a', 'aa', 'aaa', 'Hello!', '11 cats'
String concatenation:
String Replication:
>>> 'Alice' * 5
'AliceAliceAliceAliceAlice'
Variables
You can name a variable anything as long as it obeys the following three rules:
Example:
Comments
Inline comment:
# This is a comment
Multiline comment:
5/59
# This is a
# multiline comment
Function docstring:
def foo():
"""
This is a function docstring
You can also use:
''' Function Docstring '''
"""
Example Code:
Output:
6/59
>>> len('hello')
5
>>> str(29)
'29'
>>> str(-3.14)
'-3.14'
Float to Integer:
>>> int(7.7)
7
>>> int(7.7) + 1
8
Flow Control
Comparison Operators
Operator Meaning
== Equal to
!= Not equal to
7/59
These operators evaluate to True or False depending on the values you give them:
Examples:
>>> 42 == 42
True
>>> 40 == 42
False
>>> 42 == 42.0
True
>>> 42 == '42'
False
Boolean Operators
Expression Evaluates to
8/59
Expression Evaluates to
Expression Evaluates to
>>> (1 == 2) or (2 == 2)
True
You can also use multiple Boolean operators in an expression, along with the comparison operators:
if Statements
if name == 'Alice':
print('Hi, Alice.')
else Statements
9/59
name = 'Bob'
if name == 'Alice':
print('Hi, Alice.')
else:
print('Hello, stranger.')
elif Statements
name = 'Bob'
age = 5
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
name = 'Bob'
age = 30
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
else:
print('You are neither Alice nor a little kid.')
spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
break Statements
If the execution reaches a break statement, it immediately exits the while loop’s clause.
while True:
10/59
print('Please type your name.')
name = input()
if name == 'your name':
break
print('Thank you!')
continue Statements
When the program execution reaches a continue statement, the program execution immediately jumps back to
the start of the loop.
while True:
print('Who are you?')
name = input()
if name != 'Joe':
continue
print('Hello, Joe. What is the password? (It is a fish.)')
password = input()
if password == 'swordfish':
break
print('Access granted.')
Output:
My name is
Jimmy Five Times (0)
Jimmy Five Times (1)
Jimmy Five Times (2)
Jimmy Five Times (3)
Jimmy Five Times (4)
The range() function can also be called with three arguments. The first two arguments will be the start and
stop values, and the third will be the step argument. The step is the amount that the variable is increased by
after each iteration.
11/59
for i in range(0, 10, 2):
print(i)
Output:
0
2
4
6
8
You can even use a negative number for the step argument to make the for loop count down instead of up.
Output:
5
4
3
2
1
0
Importing Modules
import random
for i in range(5):
print(random.randint(1, 10))
12/59
Return to the Top
import sys
while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
sys.exit()
print('You typed ' + response + '.')
Functions
def hello(name):
print('Hello ' + name)
hello('Alice')
hello('Bob')
Output:
Hello Alice
Hello Bob
When creating a function using the def statement, you can specify what the return value should be with a
return statement. A return statement consists of the following:
import random
def getAnswer(answerNumber):
if answerNumber == 1:
return 'It is certain'
elif answerNumber == 2:
13/59
return 'It is decidedly so'
elif answerNumber == 3:
return 'Yes'
elif answerNumber == 4:
return 'Reply hazy try again'
elif answerNumber == 5:
return 'Ask again later'
elif answerNumber == 6:
return 'Concentrate and ask again'
elif answerNumber == 7:
return 'My reply is no'
elif answerNumber == 8:
return 'Outlook not so good'
elif answerNumber == 9:
return 'Very doubtful'
r = random.randint(1, 9)
fortune = getAnswer(r)
print(fortune)
print('Hello', end='')
print('World')
Output:
HelloWorld
14/59
>>> print('cats', 'dogs', 'mice', sep=',')
cats,dogs,mice
Code in a function’s local scope cannot use variables in any other local scope.
You can use the same name for different variables if they are in different scopes. That is, there can be a
local variable named spam and a global variable also named spam.
If you need to modify a global variable from within a function, use the global statement:
def spam():
global eggs
eggs = 'spam'
eggs = 'global'
spam()
print(eggs)
Output:
spam
There are four rules to tell whether a variable is in a local scope or global scope:
1. If a variable is being used in the global scope (that is, outside of all functions), then it is always a global
variable.
3. Otherwise, if the variable is used in an assignment statement in the function, it is a local variable.
15/59
Return to the Top
Exception Handling
def spam(divideBy):
try:
return 42 / divideBy
except ZeroDivisionError:
print('Error: Invalid argument.')
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
Output:
21.0
3.5
Error: Invalid argument.
None
42.0
Lists
>>> spam
['cat', 'bat', 'rat', 'elephant']
>>> spam[0]
'cat'
>>> spam[1]
'bat'
16/59
>>> spam[2]
'rat'
>>> spam[3]
'elephant'
Negative Indexes
>>> spam[-3]
'bat'
>>> 'The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.'
'The elephant is afraid of the bat.'
>>> spam[0:4]
['cat', 'bat', 'rat', 'elephant']
>>> spam[1:3]
['bat', 'rat']
>>> spam[0:-1]
['cat', 'bat', 'rat']
>>> spam[:2]
['cat', 'bat']
>>> spam[1:]
['bat', 'rat', 'elephant']
>>> spam[:]
['cat', 'bat', 'rat', 'elephant']
17/59
Return to the Top
>>> len(spam)
3
>>> spam
['cat', 'aardvark', 'rat', 'elephant']
>>> spam
['cat', 'aardvark', 'aardvark', 'elephant']
>>> spam
['cat', 'aardvark', 'aardvark', 12345]
>>> spam
18/59
[1, 2, 3, 'A', 'B', 'C']
>>> spam
['cat', 'bat', 'elephant']
>>> spam
['cat', 'bat']
Output:
19/59
>>> 'cat' in spam
False
The multiple assignment trick is a shortcut that lets you assign multiple variables with the values in a list in one
line of code. So instead of doing this:
The multiple assignment trick can also be used to swap the values in two variables:
>>> a, b = b, a
>>> print(a)
'Bob'
>>> print(b)
'Alice'
20/59
Augmented Assignment Operators
Operator Equivalent
Examples:
>>> spam.index('Pooka')
1
append():
>>> spam.append('moose')
>>> spam
['cat', 'dog', 'bat', 'moose']
21/59
inser t():
>>> spam
['cat', 'chicken', 'dog', 'bat']
>>> spam.remove('bat')
>>> spam
['cat', 'rat', 'elephant']
If the value appears multiple times in the list, only the first instance of the value will be removed.
>>> spam.sort()
>>> spam
[-7, 1, 2, 3.14, 5]
>>> spam.sort()
>>> spam
['ants', 'badgers', 'cats', 'dogs', 'elephants']
You can also pass True for the reverse keyword argument to have sort() sort the values in reverse order:
>>> spam.sort(reverse=True)
22/59
>>> spam
['elephants', 'dogs', 'cats', 'badgers', 'ants']
If you need to sort the values in regular alphabetical order, pass str. lower for the key keyword argument in the
sort() method call:
>>> spam.sort(key=str.lower)
>>> spam
['a', 'A', 'z', 'Z']
>>> eggs[0]
'hello'
>>> eggs[1:3]
(42, 0.5)
>>> len(eggs)
3
The main way that tuples are different from lists is that tuples, like strings, are immutable.
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
23/59
Return to the Top
values():
Output:
red
42
keys():
Output:
color
age
items():
24/59
Output:
('color', 'red')
('age', 42)
Using the keys(), values(), and items() methods, a for loop can iterate over the keys, values, or key-value pairs
in a dictionary, respectively
Output:
>>> # You can omit the call to keys() when checking for a key
>>> 'color' in spam
False
25/59
The get() Method
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}
Pretty Printing
import pprint
message = 'It was a bright cold day in April, and the clocks were striking
thirteen.'
count = {}
26/59
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
Output:
Manipulating Strings
Escape Characters
\t Tab
\ Backslash
27/59
Example:
Output:
Hello there!
How are you?
I'm doing fine.
Raw Strings
A raw string completely ignores all escape characters and prints any backslash that appears in the string.
Output:
print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob''')
Output:
Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
28/59
Sincerely,
Bob
H e l l o w o r l d !
0 1 2 3 4 5 6 7 8 9 10 11
>>> spam[0]
'H'
>>> spam[4]
'o'
>>> spam[-1]
'!'
>>> spam[0:5]
'Hello'
>>> spam[:5]
'Hello'
>>> spam[6:]
'world!'
Slicing:
>>> fizz
'Hello'
29/59
>>> 'Hello' in 'Hello World'
True
>>> spam
'HELLO WORLD!'
>>> spam
'hello world!'
>>> spam.islower()
False
>>> spam.isupper()
False
>>> 'HELLO'.isupper()
True
30/59
>>> 'abc12345'.islower()
True
>>> '12345'.islower()
False
>>> '12345'.isupper()
False
isalpha() returns True if the string consists only of letters and is not blank.
isalnum() returns True if the string consists only of lettersand numbers and is not blank.
isdecimal() returns True if the string consists only ofnumeric characters and is not blank.
isspace() returns True if the string consists only of spaces,tabs, and new-lines and is not blank.
istitle() returns True if the string consists only of wordsthat begin with an uppercase letter followed by
onlylowercase letters.
>>> 'abc123'.startswith('abcdef')
False
>>> 'abc123'.endswith('12')
False
join():
31/59
>>> ', '.join(['cats', 'rats', 'bats'])
'cats, rats, bats'
split():
>>> 'MyABCnameABCisABCSimon'.split('ABC')
['My', 'name', 'is', 'Simon']
>>> 'Hello'.rjust(10)
' Hello'
>>> 'Hello'.rjust(20)
' Hello'
>>> 'Hello'.ljust(10)
'Hello '
An optional second argument to rjust() and ljust() will specify a fill character other than a space character. Enter
the following into the interactive shell:
32/59
'Hello---------------'
center():
>>> 'Hello'.center(20)
' Hello '
>>> spam.strip()
'Hello World'
>>> spam.lstrip()
'Hello World '
>>> spam.rstrip()
' Hello World'
'BaconSpamEggs'
>>> pyperclip.paste()
'Hello world!'
33/59
Regular Expressions
1. Import the regex module with import re.
2. Create a Regex object with the re.compile() function. (Remember to use a raw string.)
3. Pass the string you want to search into the Regex object’s search() method. This returns a Match object.
4. Call the Match object’s group() method to return a string of the actual matched text.
>>> import re
>>> mo.group(1)
'415'
>>> mo.group(2)
'555-4242'
>>> mo.group(0)
'415-555-4242'
>>> mo.group()
'415-555-4242'
To retrieve all the groups at once: groups() method—note the plural form for the name.
34/59
>>> mo.groups()
('415', '555-4242')
>>> print(area_code)
415
>>> print(main_number)
555-4242
The | character is called a pipe. You can use it anywhere you want to match one of many expressions. For
example, the regular expression r'Batman|Tina Fey' will match either 'Batman' or 'Tina Fey'.
>>> mo1.group()
'Batman'
>>> mo2.group()
'Tina Fey'
You can also use the pipe to match one of several patterns as part of your regex:
>>> mo.group()
'Batmobile'
>>> mo.group(1)
'mobile'
35/59
The ? character flags the group that precedes it as an optional part of the pattern.
The * (called the star or asterisk) means “match zero or more”—the group that precedes the star can occur any
number of times in the text.
While * means “match zero or more,” the + (or plus) means “match one or more”. The group preceding a plus
must appear at least once. It is not optional:
36/59
>>> mo3 = bat_regex.search('The Adventures of Batman')
>>> mo3 is None
True
If you have a group that you want to repeat a specific number of times, follow the group in your regex with a
number in curly brackets. For example, the regex (Ha){3} will match the string 'HaHaHa', but it will not match
'HaHa', since the latter has only two repeats of the (Ha) group.
Instead of one number, you can specify a range by writing a minimum, a comma, and a maximum in between
the curly brackets. For example, the regex (Ha){3,5} will match 'HaHaHa', 'HaHaHaHa', and 'HaHaHaHaHa'.
Python’s regular expressions are greedy by default, which means that in ambiguous situations they will match
the longest string possible. The non-greedy version of the curly brackets, which matches the shortest string
possible, has the closing curly bracket followed by a question mark.
37/59
In addition to the search() method, Regex objects also have a findall() method. While search() will return a
Match object of the first matched text in the searched string, the findall() method will return the strings of
every match in the searched string.
When called on a regex with no groups, such as \d-\d\d\d-\d\d\d\d, the method findall() returns a list of
ng matches, such as ['415-555-9999', '212-555-0000'].
When called on a regex that has groups, such as (\d\d\d)-d\d)-(\d\ d\d\d), the method findall() returns a
list of es of strings (one string for each group), such as [('415', ', '9999'), ('212', '555', '0000')].
There are times when you want to match a set of characters but the shorthand character classes (\d, \w, \s, and
so on) are too broad. You can define your own character class using square brackets. For example, the
character class [aeiouAEIOU] will match any vowel, both lowercase and uppercase.
You can also include ranges of letters or numbers by using a hyphen. For example, the character class [a-zA-
Z0-9] will match all lowercase letters, uppercase letters, and numbers.
By placing a caret character (^) just after the character class’s opening bracket, you can make a negative
character class. A negative character class will match all the characters that are not in the character class. For
example, enter the following into the interactive shell:
38/59
The Caret and Dollar Sign Characters
You can also use the caret symbol (^) at the start of a regex to indicate that a match must occur at the
beginning of the searched text.
Likewise, you can put a dollar sign ($) at the end of the regex to indicate the string must end with this
regex pattern.
And you can use the ^ and $ together to indicate that the entire string must match the regex—that is,
it’s not enough for a match to be made on some subset of the string.
The r'^Hello' regular expression string matches strings that begin with 'Hello':
The r'\d$' regular expression string matches strings that end with a numeric character from 0 to 9:
>>> whole_string_is_num.search('1234567890')
<_sre.SRE_Match object; span=(0, 10), match='1234567890'>
The . (or dot) character in a regular expression is called a wildcard and will match any character except for a
newline:
39/59
Return to the Top
>>> mo.group(1)
'Al'
>>> mo.group(2)
'Sweigart'
The dot-star uses greedy mode: It will always try to match as much text as possible. To match any and all text
in a nongreedy fashion, use the dot, star, and question mark (.*?). The question mark tells Python to match in a
nongreedy way:
The dot-star will match everything except a newline. By passing re.DOTALL as the second argument to
re.compile(), you can make the dot character match all characters, including the newline character:
40/59
Return to the Top
Symbol Matches
\D, \W, and \S anything except a digit, word, or space acter, respectively.
Case-Insensitive Matching
To make your regex case-insensitive, you can pass re.IGNORECASE or re.I as a second argument to re.compile():
>>> robocop.search('Al, why does your programming book talk about robocop so
much?').group()
'robocop'
41/59
Return to the Top
Another example:
To tell the re.compile() function to ignore whitespace and comments inside the regular expression string,
“verbose mode” can be enabled by passing the variable re.VERBOSE as the second argument to re.compile().
phone_regex = re.compile(r'((\d{3}|\(\d{3}\))?(\s|-|\.)?\d{3}(\s|-|\.)\d{4}
(\s*(ext|x|ext.)\s*\d{2,5})?)')
you can spread the regular expression over multiple lines with comments like this:
phone_regex = re.compile(r'''(
(\d{3}|\(\d{3}\))? # area code
(\s|-|\.)? # separator
\d{3} # first 3 digits
(\s|-|\.) # separator
42/59
\d{4} # last 4 digits
(\s*(ext|x|ext.)\s*\d{2,5})? # extension
)''', re.VERBOSE)
On Windows, paths are written using backslashes () as the separator between folder names. OS X and Linux,
however, use the forward slash (/) as their path separator.
Fortunately, this is simple to do with the os.path.join() function. If you pass it the string values of individual file
and folder names in your path, os.path.join() will return a string with a file path using the correct path
separators.
>>> import os
The os.path.join() function is helpful if you need to create strings for filenames:
Output:
C:\Users\asweigart\accounts.txt
C:\Users\asweigart\details.csv
C:\Users\asweigart\invite.docx
>>> import os
>>> os.getcwd()
'C:\\Python34'
43/59
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
There are also the dot (.) and dot-dot (..) folders. These are not real folders but special names that can be used
in a path. A single period (“dot”) for a folder name is shorthand for “this directory.” Two periods (“dot-dot”)
means “the parent folder.”
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
Calling os.path.abspath(path) will return a string of the absolute path of the argument. This is an easy
way to convert a relative path into an absolute one.
Calling os.path.isabs(path) will return True if the argument is an absolute path and False if it is a relative
path.
Calling os.path.relpath(path, start) will return a string of a relative path from the start path to path. If
start is not provided,the current working directory is used as the start path.
Calling os.path.getsize(path) will return the size in bytes of the file in the path argument.
Calling os.listdir(path) will return a list of filename strings for each file in the path argument. (Note that
this function is in the os module, not os.path.)
>>> os.path.getsize('C:\\Windows\\System32\\calc.exe')
44/59
776192
>>> os.listdir('C:\\Windows\\System32')
['0409', '12520437.cpx', '12520850.cpx', '5U877.ax', 'aaclient.dll',
--snip--
'xwtpdui.dll', 'xwtpw32.dll', 'zh-CN', 'zh-HK', 'zh-TW', 'zipfldr.dll']
To find the total size of all the files in this directory, use os.path.getsize() and os.listdir() together:
>>> total_size = 0
>>> print(total_size)
1117846456
Calling os.path.exists(path) will return True if the file or er referred to in the argument exists and will
return False t does not exist.
Calling os.path.isfile(path) will return True if the path ment exists and is a file and will return False
otherwise.
Calling os.path.isdir(path) will return True if the path ment exists and is a folder and will return False
otherwise.
To read/write to a file in Python, you will want to use the with statement, which will close the file for you after
you are done.
45/59
>>> # Alternatively, you can use the *readlines()* method to get a list of
string values from the file, one string for each line of text:
>>> # You can also iterate through the file line by line:
>>> with open('sonnet29.txt') as sonnet_file:
... for line in sonnet_file: # note the new line character will be
included in the line
... print(line, end='')
Writing to Files
>>> print(content)
Hello world!
Bacon is not a vegetable.
To save variables:
46/59
>>> cats = ['Zophie', 'Pooka', 'Simon']
>>> with shelve.open('mydata') as shelf_file:
... shelf_file['cats'] = cats
Just like dictionaries, shelf values have keys() and values() methods that will return list-like values of the keys
and values in the shelf. Since these methods return list-like values instead of true lists, you should pass them to
the list() function to get them in list form.
>>> pprint.pformat(cats)
"[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]"
The shutil module provides functions for copying files, as well as entire folders.
47/59
>>> import shutil, os
>>> os.chdir('C:\\')
While shutil.copy() will copy a single file, shutil.copytree() will copy an entire folder and every folder and file
contained in it:
>>> os.chdir('C:\\')
The destination path can also specify a filename. In the following example, the source file is moved and
renamed:
If there is no eggs folder, then move() will rename bacon.txt to a file named eggs.
48/59
Permanently Deleting Files and Folders
Calling os.rmdir(path) will delete the folder at path. This folder must be empty of any files or folders.
Calling shutil.rmtree(path) will remove the folder at path, and all files and folders it contains will also be
deleted.
You can install this module by running pip install send2trash from a Terminal window.
>>> send2trash.send2trash('bacon.txt')
import os
print('')
Output:
49/59
The current folder is C:\delicious\cats
FILE INSIDE C:\delicious\cats: catnames.txt
FILE INSIDE C:\delicious\cats: zophie.jpg
The extractall() method for ZipFile objects extracts all the files and folders from a ZIP file into the current
working directory.
The extract() method for ZipFile objects will extract a single file from the ZIP file. Continue the interactive shell
example:
50/59
>>> with zipfile.ZipFile('example.zip') as example_zip:
... print(example_zip.extract('spam.txt'))
... print(example_zip.extract('spam.txt', 'C:\\some\\new\\folders'))
'C:\\spam.txt'
'C:\\some\\new\\folders\\spam.txt'
This code will create a new ZIP file named new.zip that has the compressed contents of spam.txt.
Debugging
Raising Exceptions
Exceptions are raised with a raise statement. In code, a raise statement consists of the following:
Often it’s the code that calls the function, not the function itself, that knows how to handle an expection. So
you will commonly see a raise statement inside a function and the try and except statements in the code
calling the function.
51/59
if height <= 2:
raise Exception('Height must be greater than 2.')
print(symbol * width)
for i in range(height - 2):
print(symbol + (' ' * (width - 2)) + symbol)
print(symbol * width)
for sym, w, h in (('*', 4, 4), ('O', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)):
try:
box_print(sym, w, h)
except Exception as err:
print('An exception happened: ' + str(err))
The traceback is displayed by Python whenever a raised exception goes unhandled. But can also obtain it as a
string by calling traceback.format_exc(). This function is useful if you want the information from an exception’s
traceback but also want an except statement to gracefully handle the exception. You will need to import
Python’s traceback module before calling this function.
>>> try:
raise Exception('This is the error message.')
except:
with open('errorInfo.txt', 'w') as error_file:
error_file.write(traceback.format_exc())
print('The traceback info was written to errorInfo.txt.')
Output:
116
The traceback info was written to errorInfo.txt.
The 116 is the return value from the write() method, since 116 characters were written to the file. The
traceback text was written to errorInfo.txt.
52/59
Assertions
An assertion is a sanity check to make sure your code isn’t doing something obviously wrong. These sanity
checks are performed by assert statements. If the sanity check fails, then an AssertionError exception is raised.
In code, an assert statement consists of the following:
In plain English, an assert statement says, “I assert that this condition holds true, and if not, there is a bug
somewhere in the program.” Unlike exceptions, your code should not handle assert statements with try and
except; if an assert fails, your program should crash. By failing fast like this, you shorten the time between the
original cause of the bug and when you first notice the bug. This will reduce the amount of code you will have
to check before finding the code that’s causing the bug.
Disabling Assertions
Logging
To enable the logging module to display log messages on your screen as your program runs, copy the
following to the top of your program (but under the #! python shebang line):
import logging
53/59
%(message)s')
Say you wrote a function to calculate the factorial of a number. In mathematics, factorial 4 is 1 × 2 × 3 × 4, or
24. Factorial 7 is 1 × 2 × 3 × 4 × 5 × 6 × 7, or 5,040. Open a new file editor window and enter the following
code. It has a bug in it, but you will also enter several log messages to help yourself figure out what is going
wrong. Save the program as factorialLog.py.
import logging
logging.debug('Start of program')
def factorial(n):
return total
print(factorial(5))
logging.debug('End of program')
Output:
54/59
Logging Levels
Logging levels provide a way to categorize your log messages by importance. There are five logging levels,
described in Table 10-1 from least to most important. Messages can be logged at each level using a different
logging function.
Logging
Level Description
Function
The lowest level. Used for small details. Usually you care about these
DEBUG logging.debug()
messages only when diagnosing problems.
ERROR logging.error() Used to record an error that caused the program to fail to do something.
The highest level. Used to indicate a fatal error that has caused or is
CRITICAL logging.critical()
about to cause the program to stop running entirely.
Disabling Logging
After you’ve debugged your program, you probably don’t want all these log messages cluttering the screen.
The logging.disable() function disables these so that you don’t have to go into your program and remove all
the logging calls by hand.
>>> logging.disable(logging.CRITICAL)
Logging to a File
55/59
Instead of displaying the log messages to the screen, you can write them to a text file. The
logging.basicConfig() function takes a filename keyword argument, like so:
import logging
logging.basicConfig(filename='myProgramLog.txt', level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s')
Virtual Environment
The use of a Virtual Environment is to test python code in encapsulated environments and to also avoid filling
the base Python installation with libraries we might use for only one project.
Windows
1. Install virtualenv:
2. Install virtualenvwrapper-win:
Usage:
mkvirtualenv HelloWold
Anything we install now will be specific to this project. And available to the projects we connect to this
environment.
To bind our virtualenv with our current working directory we simply enter:
setprojectdir .
56/59
3. Deactivate:
To move onto something else in the command line type ‘deactivate’ to deactivate your environment.
deactivate
4. Workon:
Open up the command prompt and type ‘workon HelloWold’ to activate the environment and move
into your root project folder:
workon HelloWold
Lambda Functions
This function:
>>> add(5, 3)
8
57/59
>>> def make_adder(n):
return lambda x: x + n
>>> plus_3(4)
7
>>> plus_5(4)
9
Example:
>>> age = 15
>>> age = 15
>>> print('kid' if age < 13 else 'teenager' if age < 18 else 'adult')
teenager
58/59
else:
print('adult')
59/59