Basic Cheat Sheet for Python (PDF, Markdown and Jupyter Notebook)
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. I have modified this to remove what you do not need to know.
| symbol | Name | symbol | Name |
|---|---|---|---|
| ‘ | Single Quote | \ | Backslash |
| “ | Double Quote | > | Greater |
| ! | Exclamation | < | Less |
| # | Hash | : | Colon |
| () | Parentheses | ; | Semi Colon |
| [] | Square bracket | {} | curly braket |
| * | Asterisk | . | Dot |
| / | Slash | , | Comma |
Parentheses () are used to assign code including strings, numbers, variables etc to a particular function
print("this string belongs to the print function")
int(input("this string belongs to the input function, the input function belongs to the int function"))
# notice the 2 closing parenthesis ^
quotation marks “” or ‘’ are used to enclose strings either double or single quotation marks can be used so long as the same are used on either side
print('I can use single or double quotes')
print("I'm going to use double quotes here because the single is used as an apostrophe')
comma , is used to seperate arguments to a function
range(5)
range (3, 8)
range (3, 8, 2)
The range function can take one, two or, three arguements white space For the most part spaces in your code do not matter you will notice above in the range command the first command had no space between range the parenthesis but the rest do There are only a few occasions it really matters if you include a space in your code or not and I will cover when that is the case
From Highest to Lowest precedence:
| Operators | Operation | Example |
|---|---|---|
| / | Division | 22 / 8 = 2.75 |
| * | Multiplication | 3 * 3 = 9 |
| - | Subtraction | 5 - 2 = 3 |
| + | Addition | 2 + 2 = 4 |
Examples of expressions in the interactive shell:
>>> 2 + 3 * 6
20
>>> (2 + 3) * 6
30
>>> (5 - 1) * ((7 + 1) / (3 - 1))
16.0
| 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' |
String concatenation:
>>> 'Alice' + 'Bob'
'AliceBob'
Note: Avoid + operator for string concatenation. Prefer fStrings except in some instances.
String Replication:
>>> 'Alice' * 5
'AliceAliceAliceAliceAlice'
You can name a variable anything as long as it obeys the following rules:
_) character._) are considered as “unuseful`.Example:
>>> spam = 'Hello'
>>> spam
'Hello'
>>> _spam = 'Hello'
_spam should not be used again in the code.
Is used to join multiple words together without spaces or _ and make it readable Example:
>>> firstName = 'John'
>>> lastName = 'Smith'
Inline comment:
# This is a comment
Multiline comment:
# This is a
# multiline comment
Code with a comment:
a = 1 # initialization
Please note the two spaces in front of the comment.
Docstring: Using 3 quotation marks you can define a multiple line comment or Docstring Start and end the docstring with 3 quotation marks of the same type
"""
This is a function docstring
With multiple
lines
"""
''' you can also
put your quotation
marks at the start and end of a line '''
>>> print('Hello world!')
Hello world!
>>> a = 1
>>> print(f'Hello world! {a}')
Hello world! 1
Example Code:
>>> print('What is your name?') # ask for their name
>>> myName = input()
>>> print(f'It is good to meet you, {myName})
What is your name?
Al
It is good to meet you, Al
Evaluates to the integer value of the number of characters in a string:
>>> len('hello')
5
Note: test of emptiness of strings, lists, dictionary, etc, should not use len, but prefer direct boolean evaluation.
>>> a = [1, 2, 3]
>>> if a:
>>> print("the list is not empty!")
Integer to String or Float:
>>> str(29)
'29'
>>> print('I am '+ str(29) +' years old.')
I am 29 years old.
You can also use fstrings to do this without the str command
>>> str(-3.14)
'-3.14'
Float to Integer:
>>> int(7.7)
7
>>> int(7.7) + 1
8
| 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.
Examples:
>>> 42 == 42
True
>>> 40 == 42
False
>>> 'hello' == 'hello'
True
>>> 'hello' == 'Hello'
False
>>> 'dog' != 'cat'
True
>>> 42 == 42.0
True
>>> 42 == '42'
False
There are three Boolean operators: and, or, and not.
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 |
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’s Truth Table:
| Expression | Evaluates to |
|---|---|
not True |
False |
not False |
True |
>>> (4 < 5) and (5 < 6)
True
>>> (4 < 5) and (9 < 6)
False
>>> (1 == 2) or (2 == 2)
True
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
When using the python keywords if, else elif, for, while, def, and you need to end the line with a : You then need to indent the lines of code you want to belong to that statement using the tab key or multiple spaces (tab is prefered)
if this == that:
this line belongs to the if statement (line 1)
so does this line (line 2)
this line does not (line 3)
What this means as we will see in the next section if this equals that line 1 and line 2 will run Line 3 will run regardless if this equals that
Any time you see a : followed by indented lines it means anything that is indented belongs to the statement with the :
if name == 'Alice':
print('Hi, Alice.')
name = 'Bob'
if name == 'Alice':
print('Hi, Alice.')
else:
print('Hello, stranger.')
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
If the execution reaches a break statement, it immediately exits the while loop’s clause:
while True:
print('Please type your name.')
name = input()
if name == 'your name':
break
print('Thank you!')
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.')
>>> print('My name is')
>>> for i in range(5):
>>> print(f'Jimmy Five Times ({i})')
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.
>>> for i in range(0, 10, 2):
>>> print(i)
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.
>>> for i in range(5, -1, -1):
>>> print(i)
5
4
3
2
1
0
This allows to specify a statement to execute in case of the full loop has been executed. Only
useful when a break condition can occur in the loop:
>>> for i in [1, 2, 3, 4, 5]:
>>> if i == 3:
>>> break
>>> else:
>>> print("only executed when no item of the list is equal to 3")
import random
for i in range(5):
print(random.randint(1, 10))
import random, sys, os, math
from random import *
import sys
while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
sys.exit()
print(f'You typed {response}.')
>>> def hello(name):
>>> print(f'Hello {name}')
>>>
>>> hello('Alice')
>>> hello('Bob')
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:
The return keyword.
The value or expression that the function should return.
import random
def getAnswer(answerNumber):
if answerNumber == 1:
return 'It is certain'
elif answerNumber == 2:
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)
Code in the global scope cannot use any local variables.
However, a local scope can access global variables.
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)
spam
There are four rules to tell whether a variable is in a local scope or global scope:
If a variable is being used in the global scope (that is, outside of all functions), then it is always a global variable.
If there is a global statement for that variable in a function, it is a global variable.
Otherwise, if the variable is used in an assignment statement in the function, it is a local variable.
But if the variable is not used in an assignment statement, it is a global variable.
>>> def spam(divideBy):
>>> try:
>>> return 42 / divideBy
>>> except ZeroDivisionError as e:
>>> print(f'Error: Invalid argument: {e}')
>>>
>>> print(spam(2))
>>> print(spam(12))
>>> print(spam(0))
>>> print(spam(1))
21.0
3.5
Error: Invalid argument: division by zero
None
42.0
Code inside the finally section is always executed, no matter if an exception has been raised or
not, and even if an exception is not caught.
>>> def spam(divideBy):
>>> try:
>>> return 42 / divideBy
>>> except ZeroDivisionError as e:
>>> print(f'Error: Invalid argument: {e}')
>>> finally:
>>> print("-- division finished --")
>>> print(spam(2))
-- division finished --
21.0
>>> print(spam(12))
-- division finished --
3.5
>>> print(spam(0))
Error: Invalid Argument division by zero
-- division finished --
None
>>> print(spam(1))
-- division finished --
42.0
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam
['cat', 'bat', 'rat', 'elephant']
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[0]
'cat'
>>> spam[1]
'bat'
>>> spam[2]
'rat'
>>> spam[3]
'elephant'
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1]
'elephant'
>>> spam[-3]
'bat'
>>> f'The {spam[-1]} is afraid of the {spam[-3]}.')
'The elephant is afraid of the bat.'
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[0:4]
['cat', 'bat', 'rat', 'elephant']
>>> spam[1:3]
['bat', 'rat']
>>> spam[0:-1]
['cat', 'bat', 'rat']
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[:2]
['cat', 'bat']
>>> spam[1:]
['bat', 'rat', 'elephant']
Slicing the complete list will perform a copy:
>>> spam2 = spam[:]
['cat', 'bat', 'rat', 'elephant']
>>> spam.append('dog')
>>> spam
['cat', 'bat', 'rat', 'elephant', 'dog']
>>> spam2
['cat', 'bat', 'rat', 'elephant']
>>> spam = ['cat', 'dog', 'moose']
>>> len(spam)
3
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[1] = 'aardvark'
>>> spam
['cat', 'aardvark', 'rat', 'elephant']
>>> spam[2] = spam[1]
>>> spam
['cat', 'aardvark', 'aardvark', 'elephant']
>>> spam[-1] = 12345
>>> spam
['cat', 'aardvark', 'aardvark', 12345]
>>> supplies = ['pens', 'staplers', 'flame-throwers', 'binders']
>>> for i, supply in enumerate(supplies):
>>> print(f'Index {i} in supplies is: {supply}')
Index 0 in supplies is: pens
Index 1 in supplies is: staplers
Index 2 in supplies is: flame-throwers
Index 3 in supplies is: binders
>>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas']
True
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> 'cat' in spam
False
>>> 'howdy' not in spam
False
>>> 'cat' not in spam
True
| Operator | Equivalent |
|---|---|
spam += 1 |
spam = spam + 1 |
spam -= 1 |
spam = spam - 1 |
spam *= 1 |
spam = spam * 1 |
spam /= 1 |
spam = spam / 1 |
spam %= 1 |
spam = spam % 1 |
Examples:
>>> spam = 'Hello'
>>> spam += ' world!'
>>> spam
'Hello world!'
>>> bacon = ['Zophie']
>>> bacon *= 3
>>> bacon
['Zophie', 'Zophie', 'Zophie']
>>> spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']
>>> spam.index('Pooka')
1
append():
>>> spam = ['cat', 'dog', 'bat']
>>> spam.append('moose')
>>> spam
['cat', 'dog', 'bat', 'moose']
insert():
>>> spam = ['cat', 'dog', 'bat']
>>> spam.insert(1, 'chicken')
>>> spam
['cat', 'chicken', 'dog', 'bat']
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> 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 = ['cat', 'bat', 'rat', 'elephant']
>>> spam.pop()
'elephant'
>>> spam
['cat', 'bat', 'rat']
>>> spam.pop(0)
'cat'
>>> spam
['bat', 'rat']
>>> spam = [2, 5, 3.14, 1, -7]
>>> spam.sort()
>>> spam
[-7, 1, 2, 3.14, 5]
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> 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)
>>> 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 = ['a', 'z', 'A', 'Z']
>>> spam.sort(key=str.lower)
>>> spam
['a', 'A', 'z', 'Z']
You can use the built-in function sorted to return a new list:
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> sorted(spam)
['ants', 'badgers', 'cats', 'dogs', 'elephants']
>>> print('''Dear Alice,
>>>
>>> Eve's cat has been arrested for catnapping, cat burglary, and extortion.
>>>
>>> Sincerely,
>>> Bob''')
Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
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 = 'Hello world!'
>>> spam[0]
'H'
>>> spam[4]
'o'
>>> spam[-1]
'!'
Slicing:
>>> spam[0:5]
'Hello'
>>> spam[:5]
'Hello'
>>> spam[6:]
'world!'
>>> spam[6:-1]
'world'
>>> spam[:-1]
'Hello world'
>>> spam[::-1]
'!dlrow olleH'
>>> spam = 'Hello world!'
>>> fizz = spam[0:5]
>>> fizz
'Hello'
>>> a = [1, 2, 3, 4]
>>> 5 in a
False
>>> 2 in a
True
upper() and lower():
>>> spam = 'Hello world!'
>>> spam = spam.upper()
>>> spam
'HELLO WORLD!'
>>> spam = spam.lower()
>>> spam
'hello world!'
>>> firstName = "john"
>>> firstName.capatilize()
'John'
isupper() and islower():
>>> spam = 'Hello world!'
>>> spam.islower()
False
>>> spam.isupper()
False
>>> 'HELLO'.isupper()
True
>>> 'abc12345'.islower()
True
>>> '12345'.islower()
False
>>> '12345'.isupper()
False
>>> name = 'Elizabeth'
>>> print (f'Hello {name}!')
'Hello Elizabeth!
It is even possible to do inline arithmetic with it:
>>> a = 5
>>> b = 10
>>> f'Five plus ten is {a + b} and not {2 * (a + b)}.'
print ('Five plus ten is 15 and not 30.')
fstings are one place where a space does matter you cannot put a space between the f and the quotation marks