Python Cheat Sheet
Python Cheat Sheet
| Aversity.com
Basics
Print print("Hello World")
Prints a string into the console.
Input
input("Whats your name")
Prints a string into the console, and
asks the user for a string input.
Comments
Adding a # symbol in the font of text lets you #This is a comment
make comments on a line of code. the print("This is not a comment")
compiler will ignore comments.
Variables
A variable give a name to a piece of data. Like my_name = "Sean"
a box with a label, it tells you what's inside my_age = 23
the box.
Page 1 Aversity.com
Python Cheat Sheet
| Aversity.com
Data Types
Integers my_number = 354
Integers are whole numbers.
Strings
A string is just a string of characters. It should my_string = "Hello"
be surrounded by double quotes.
String Concatenation
You can add strings to a string to create a new string. "Hello" + "Angela"
This is called concatenation. It results in a new string. #becomes "HelloAngela"
F-Strings
days = 365
You can insert a variable into a string using f-strings.
print(f"There are {days}
The syntax is simple, just insert the variable in-between
in a year")
a set of curly braces {}.
Page 2 Aversity.com
Python Cheat Sheet
| Aversity.com
Page 3 Aversity.com
Python Cheat Sheet
| Aversity.com
MATHS
Arithmetic Operators 3+2 #Add
4-1 #Subtract
You can do mathematical
2*3 #Multiply
calculations with Python as long as
5/2 #Divide
you know the right operators.
5**2 #Exponent
The += Operator
This is a convenient way to modify a
my_number = 4
variable. It takes the existing value in
my_number += 2
a variable and adds to it. You can also
#result is 6
use any of the other mathematical
operators e.g. -= or *=
Page 4 Aversity.com
Python Cheat Sheet
| Aversity.com
ERRORS
Syntax Error
Syntax errors happen when your print(12 + 4))
code does not make any sense to the File "<stdin>", line 1
computer. This can happen because print(12 + 4))
you've misspelt something or there's ^
too many brackets or a missing SyntaxError: unmatched ')'
comma.
Name Error
This happens when there is a variable
my_number = 4
with a name that the computer does
my_Number + 2
not recognise. It's usually because
Traceback (most recent call
you've misspelt the name of a variable
last): File "<stdin>", line 1,
you created earlier. Note: variable
NameError: name 'my_Number'
names are case sensitive!
is not defined
Page 5 Aversity.com
Python Cheat Sheet
| Aversity.com
FUNCTIONS
Creating Functions
This is the basic syntax for a function
in Python. It allows you to give a set def my_function():
of instructions a name, so you can print("Hello")
trigger it multiple times without name = input("Your name:")
having to re-write or copy-paste it. print("Hello")
The contents of the function must be
indented to signal that it's inside.
Calling Functions
You activate the function by calling
it. This is simply done by writing the my_function()
name of the function followed by a my_function()
set of round brackets. This allows you #The function my_function
to determine when to trigger the #will run twice.
function and how many times.
Page 6 Aversity.com
Python Cheat Sheet
| Aversity.com
Variable Scope
Variables created inside a function n = 2
are destroyed once the function has def my_function():
executed. The location (line of code) n = 3
that you use a variable will print(n)
determine its value. Here n is 2 but
inside my_function() n is 3. So print(n) #Prints 2
printing n inside and outside the my_function() #Prints 3
function will determine its value.
Keyword Arguments
def divide(n1, n2):
When calling a function, you can
result = n1 / n2
provide a keyword argument or
#Option 1:
simply just the value. Using a
divide(10, 5)
keyword argument means that you
#Option 2:
don't have to follow any order when
divide(n2=5, n1=10)
providing the inputs.
Page 7 Aversity.com
Python Cheat Sheet
| Aversity.com
CONDITIONALS
If
This is the basic syntax to test if a
n = 5
condition is true. If so, the indented
if n > 2:
code will be executed, if not it will be
print("Larger than 2")
skipped.
Else age = 18
This is a way to specify some code if age > 16:
that will be executed if a condition is print("Can drive")
false. else:
print("Don't drive")
Page 8 Aversity.com
Python Cheat Sheet
| Aversity.com
and s = 58
if s < 60 and s > 50:
This expects both conditions either
print("Your grade is C")
side of the and to be true.
or
This expects either of the conditions age = 12
either side of the or to be true. if age < 16 or age > 200:
Basically, both conditions cannot be print("Can't drive")
false.
not
if not 3 > 1:
This will flip the original result of the
print("something")
condition. e.g. if it was true then it's
#Will not be printed.
now false.
comparison operators
These mathematical comparison > Greater than
operators allow you to refine your < Lesser than
conditional checks. >= Greater than or equal to
<= Lesser than or equal to
== Is equal to
!= Is not equal to
Page 9 Aversity.com
Python Cheat Sheet
| Aversity.com
LOOPS
While Loop
This is a loop that will keep repeating n = 1
itself until the while condition while n < 100:
becomes false. n += 1
For Loop
For loops give you more control than all_fruits = ["apple",
while loops. You can loop through "banana", "orange"]
anything that is iterable. e.g. a range, for fruit in all_fruits:
a list, a dictionary or tuple. print(fruit)
_ in a For Loop
If the value your for loop is iterating
through, e.g. the number in the for _ in range(100):
range, or the item in the list is not #Do something 100 times.
needed, you can replace it with an
underscore.
Page 10 Aversity.com
Python Cheat Sheet
| Aversity.com
continue n = 0
while n < 100:
This keyword allows you to skip this n += 1
iteration of the loop and go to the if n % 2 == 0:
next. The loop will still continue, but continue
it will start from the top. print(n)
#Prints all the odd numbers
Infinite Loops
Sometimes, the condition you are
checking to see if the loop should
while 5 > 1:
continue never becomes false. In this
print("I'm a survivor")
case, the loop will continue for
eternity (or until your computer stops
it). This is more common with while
loops.
Page 11 Aversity.com
Python Cheat Sheet
| Aversity.com
LIST METHODS
Adding Lists Together list1 = [1, 2, 3]
You can extend a list with another list2 = [9, 8, 7]
list by using the extend keyword, or new_list = list1 + list2
the + symbol. list1 += list2
List Index
letters = ["a", "b", "c"]
To get hold of a particular item from a
letters[0]
list you can use its index number. This
#Result:"a"
number can also be negative, if you
letters[-1]
want to start counting from the end of
#Result: "c"
the list.
List Slicing
#list[start:end]
Using the list index and the colon
letters = ["a","b","c","d"]
symbol you can slice up a list to get
letters[1:3]
only the portion you want. Start is
#Result: ["b", "c"]
included, but end is not.
Page 12 Aversity.com
Python Cheat Sheet
| Aversity.com
BUILT IN FUNCTIONS
Range
# range(start, end, step)
Often you will want to generate a
for i in range(6, 0, -2):
range of numbers. You can specify
print(i)
the start, end and step. Start is
# result: 6, 4, 2
included, but end is excluded: start
# 0 is not included.
<= range < end
Randomisation
The random functions come from import random
the random module which needs to # randint(start, end)
be imported. In this case, the start n = random.randint(2, 5)
and end are both included start <= #n can be 2, 3, 4 or 5.
randint <= end
Round
This does a mathematical round. So round(4.6)
3.1 becomes 3, 4.5 becomes 5 and 5.8 # result 5
becomes 6.
abs
This returns the absolute value. abs(-4.6)
Basically removing any -ve signs. # result 4.6
Page 13 Aversity.com
Python Cheat Sheet
| Aversity.com
MODULES
Importing
Some modules are pre-installed with import random
python e.g. random/datetime Other n = random.randint(3, 10)
modules need to be installed from
pypi.org
Aliasing
You can use the as keyword to give import random as r
your module a different name. n = r.randint(1, 5)
Page 14 Aversity.com
Python Cheat Sheet
| Aversity.com
Class Variables
class Car:
You can create a varaiable in a class.
colour = "black"
The value of the variable will be
car1 = Car()
available to all objects created from
print(car1.colour) #black
the class.
Page 15 Aversity.com
Python Cheat Sheet
| Aversity.com
Class Properties
You can create a variable in the init() class Car:
of a class so that all objects created def __init__(self, name):
from the class has access to that self.name = "Jimmy"
variable.
Page 16 Aversity.com