PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
P
BASICS
Print
Prints a string into the console. print("Hello World")
Input
Prints a string into the console,
input("What's your name")
and asks the user for a string input.
Comments
Adding a # symbol in font of text
lets you make comments on a line of code. #This is a comment
The computer will ignore your comments. print("This is code")
Variables
A variable give a name to a piece of
my_name = "Angela"
data. Like a box with a label, it tells you
what's inside the box. my_age = 12
The += Operator
This is a convient way of saying: "take
my_age = 12
the previous value and add to it.
my_age += 4
#my_age is now 16
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
DATATYPES P
Integers
Integers are whole numbers. my_number = 354
Floating Point Numbers
Floats are numbers with decimal places.
my_float = 3.14159
When you do a calculation that results in
a fraction e.g. 4 ÷ 3 the result will always be
a floating point number.
Strings
A string is just a string of characters.
my_string = "Hello"
It should be surrounded by double quotes.
String Concatenation
You can add strings to string to create
a new string. This is called "Hello" + "Angela"
concatenation. It results in a new string. #becomes "HelloAngela"
Escaping a String
Because the double quote is special, it
speech = "She said: \"Hi\""
denotes a string, if you want to use it in
a string, you need to escape it with a "\" print(speech)
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
#prints: She said: "Hi" P
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
P
F-Strings
You can insert a variable into a string days = 365
using f-strings.
print(f"There are {days}
The syntax is simple, just insert the
variable in-between a set of curly braces {}. in a year")
Converting Data Types
You can convert a variable from 1 data
type to another. n = 354
Converting to float: new_n = float(n)
float()
Converting to int:
print(new_n) #result 354.0
int()
Converting to string:
str()
Checking Data Types
You can use the type() function n = 3.14159
to check what is the data type of a
type(n) #result float
particular variable.
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
MATHS P
Arithmetic Operators
You can do mathematical calculations with 3+2 #Add
Python as long as you know the right
4-1 #Subtract
operators.
2*3 #Multiply
5/2 #Divide
5**2 #Exponent
The += Operator
This is a convenient way to modify a
variable.
my_number = 4
It takes the existing value in a variable my_number += 2
and adds to it. #result is 6
You can also use any of the other
mathematical operators e.g. -= or *=
The Modulo Operator
Often you'll want to know what is
the remainder after a division. 5 % 2
e.g. 4 ÷ 2 = 2 with no remainder #result is 1
but 5 ÷ 2 = 2 with 1 remainder
The modulo does not give you the result
of the division, just the remainder.
It can be really helpful in certain situations,
e.g. figuring out if a number is odd or even.
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
P
ERRORS
Syntax Error
Syntax errors happen when your code
print(12 + 4))
does not make any sense to the computer.
This can happen because you've misspelt File "<stdin>", line 1
something or there's too many brackets or print(12 + 4))
a missing comma. ^
SyntaxError: unmatched ')'
Name Error
This happens when there is a variable
my_number = 4
with a name that the computer
does not recognise. It's usually my_Number + 2
because you've misspelt the name of a Traceback (most recent call
variable you created earlier. last): File "<stdin>", line 1,
Note: variable names are case
NameError: name 'my_Number'
sensitive!
is not defined
Zero Division Error
This happens when you try to divide by zero, 5 % 0
This is something that is mathematically Traceback (most recent call
impossible so Python will also complain.
last): File "<stdin>", line 1,
ZeroDivisionError: integer
division or modulo by zero
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
P
FUNCTIONS
Creating Functions
def my_function():
This is the basic syntax for a function in
Python. It allows you to give a set of print("Hello")
instructions a name, so you can trigger it name = input("Your name:")
multiple times without having to re-
print("Hello")
write
or copy-paste it. The contents of the function
must be indented to signal that it's inside.
Calling Functions
You activate the function by calling it.
my_function()
This is simply done by writing the name of my_function()
the function followed by a set of round #The function my_function
brackets. This allows you to determine
#will run twice.
when to trigger the function and how
many times.
Functions with Inputs
In addition to simple functions, you can def add(n1, n2):
give the function an input, this way, each time
print(n1 + n2)
the function can do something different
depending on the input. It makes your
function more useful and re-usable. add(2, 3)
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
P
Functions with Outputs
In addition to inputs, a function can also have def add(n1, n2):
an output. The output value is proceeded by
return n1 + n2
the keyword "return".
This allows you to store the result from a
function. result = add(2, 3)
Variable Scope
Variables created inside a function are n = 2
destroyed once the function has executed. def my_function():
The location (line of code) that you use n = 3
a variable will determine its value.
Here n is 2 but inside my_function() n is 3.
print(n)
So printing n inside and outside the function
will determine its value. print(n) #Prints 2
my_function() #Prints 3
Keyword Arguments
def divide(n1, n2):
When calling a function, you can provide
a keyword argument or simply just the
result = n1 / n2
value. #Option 1:
Using a keyword argument means that divide(10, 5)
you don't have to follow any order
#Option 2:
when providing the inputs.
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
divide(n2=5, P
n1=10)
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
P
CONDITIONALS
If
n = 5
This is the basic syntax to test if a condition
if n > 2:
is true. If so, the indented code will be
executed, if not it will be skipped. print("Larger than 2")
Else
age = 18
This is a way to specify some code that will
be executed if a condition is false.
if age > 16:
print("Can drive")
else:
print("Don't drive")
Elif
In addition to the initial If statement weather = "sunny"
condition, you can add extra conditions to
if weather == "rain":
test if the first condition is false.
Once an elif condition is true, the rest of print("bring umbrella")
the elif conditions are no longer checked elif weather == "sunny":
and are skipped. print("bring sunglasses")
elif weather == "snow":
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
print("bring gloves") P
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
P
and
This expects both conditions either side
s = 58
of the and to be true. if s < 60 and s > 50:
print("Your grade is C")
or
age = 12
This expects either of the conditions either
side of the or to be true. Basically, both
if age < 16 or age > 200:
conditions cannot be false. print("Can't drive")
not
This will flip the original result of the
if not 3 > 1:
condition. e.g. if it was true then it's
now false. print("something")
#Will not be printed.
comparison operators
These mathematical comparison operators > Greater than
allow you to refine your conditional checks.
< Lesser than
>= Greater than or equal to
<= Lesser than or equal to
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
== Is equal to P
!= Is not equal to
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
P
LOOPS
While Loop
n = 1
This is a loop that will keep repeating itself
while n < 100:
until the while condition becomes false.
n += 1
For Loop
For loops give you more control than all_fruits = ["apple",
while loops. You can loop through anything "banana", "orange"]
that is iterable. e.g. a range, a list, a
for fruit in all_fruits:
dictionary or tuple.
print(fruit)
_ in a For Loop
If the value your for loop is iterating
through, for _ in range(100):
e.g. the number in the range, or the item in #Do something 100 times.
the list is not needed, you can replace it with
an underscore.
break
This keyword allows you to break free of the scores = [34, 67, 99, 105]
loop. You can use it in a for or while loop. for s in scores:
if s > 100:
print("Invalid")
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
break P
print(s)
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
P
continue
n = 1
This keyword allows you to skip this iteration
while n < 100:
of the loop and go to the next. The loop will
still continue, but it will start from the top. if n % 2 == 0:
continue
print(n)
#Prints all the odd numbers
Infinite Loops
while 5 > 1:
Sometimes, the condition you are checking
print("I'm a survivor")
to see if the loop should continue never
becomes false. In this case, the loop will
continue for eternity (or until your computer
stops it). This is more common with while
loops.
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
P
LIST METHODS
Adding Lists Together
list1 = [1, 2, 3]
You can extend a list with another list by
list2 = [9, 8, 7]
using the extend keyword, or the +
symbol. new_list = list1 + list2
list1 += list2
Adding an Item to a List
If you just want to add a single item to a all_fruits = ["apple",
list, you need to use the .append() "banana", "orange"]
method. all_fruits.append("pear")
List Index Start is included, but end is not.
To get hold of a particular item from a
list you can use its index number.
This number can also be negative, if you
want to start counting from the end of the
list.
List Slicing
Using the list index and the colon symbol
you can slice up a list to get only the
portion you want.
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
P
letters = ["a", "b",
"c"] letters[0]
#Result
:"a"
letters
[-1]
#Result
: "c"
#list[start:end]
letters =
["a","b","c","d"]
letters[1:3]
#Result: ["b", "c"]
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
P
BUILT IN FUNCTIONS
Range
# range(start, end, step)
Often you will want to generate a range
of numbers. You can specify the start, end for i in range(6, 0, -2):
and step. print(i)
Start is included, but end is excluded:
start >= range < end
# result: 6, 4, 2
# 0 is not included.
Randomisation
import random
The random functions come from the
random module which needs to be # randint(start, end)
imported. n = random.randint(2, 5)
In this case, the start and end are both
#n can be 2, 3, 4 or 5.
included
start <= randint <= end
Round
This does a mathematical round.
So 3.1 becomes 3, 4.5 becomes round(4.6)
5
and 5.8 becomes 6. # result 5
abs
This returns the absolute value.
Basically removing any -ve signs. abs(-4.6)
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
# result 4.6 P
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
P
MODULES
Importing
import random
Some modules are pre-installed with python
e.g. random/datetime n = random.randint(3, 10)
Other modules need to be installed from
pypi.org
Aliasing
You can use the as keyword to import random as r
give your module a different name. n = r.randint(1, 5)
Importing from modules
from random import randint
You can import a specific thing from a
n = randint(1, 5)
module. e.g. a
function/class/constant You do this
with the from keyword.
It can save you from having to type the
same thing many times.
Importing Everything
You can use the wildcard (*) to import from random import *
everything from a module. Beware, this list = [1, 2, 3]
usually reduces code readability.
choice(list)
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
# More P
readable/understood
#random.choice(list)
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
P
CLASSES & OBJECTS
Creating a Python Class
class MyClass:
You create a class using the class keyword.
Note, class names in Python are #define class
PascalCased. So to create an empty class □
Creating an Object from a Class
class Car:
You can create a new instance of an
pass
object by using the class name + ()
my_toyota = Car()
Class Methods
You can create a function that belongs class Car:
to a class, this is known as a method. def drive(self):
print("move")
my_honda = Car()
my_honda.drive()
Class Variables
You can create a varaiable in a class. class Car:
The value of the variable will be available colour = "black"
to all objects created from the class. car1 = Car()
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
print(car1.colour) P
#black
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
P
The init method
class Car:
The init method is called every time a new
def init (self):
object is created from the class.
print("Building car")
my_toyota = Car()
#You will see "building car"
#printed.
Class Properties
You can create a variable in the init() of class Car:
a class so that all objects created from the def init (self, name):
class has access to that variable.
self.name = "Jimmy"
Class Inheritance
class Animal:
When you create a new class, you
def breathe(self):
can inherit the methods and
properties of another class. print("breathing")
class Fish(Animal):
def breathe(self):
super.breathe()
print("underwater")
nemo = Fish()
nemo.breathe()
#Result:
#breathing
www. a p p b r e w e r y . c
PYTHON CHEAT SHEET
100 DAYS OF COD
C O M P L EET E P R O F E S S I O N A L
PYTHON BOOTCAM
#underwater P
www. a p p b r e w e r y . c