Datateach - Ai Python Cheat Sheet
Datateach - Ai Python Cheat Sheet
BASICS
Print
Prints a string into the console.
print("Hello World")
Input
Prints a string into the console,
and asks the user for a string input. input("What's your name")
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 data.
Like a box with a label, it tells you what's my_name = "Angela"
inside the box. my_age = 12
The += Operator
This is a convient way of saying: "take the
previous value and add to it. my_age = 12
my_age += 4
#my_age is now 16
www.datateach.ai
PYTHON CHEAT SHEET
DATA TYPES
Integers
Integers are whole numbers.
my_number = 354
Strings
A string is just a string of characters.
It should be surrounded by double quotes. my_string = "Hello"
String Concatenation
You can add strings to string to create
a new string. This is called concatenation. "Hello" + "Angela"
It results in a new string. #becomes "HelloAngela"
Escaping a String
Because the double quote is special, it
denotes a string, if you want to use it in speech = "She said: \"Hi\""
a string, you need to escape it with a "\" print(speech)
#prints: She said: "Hi"
www.datateach.ai
PYTHON CHEAT SHEET
F-Strings
You can insert a variable into a string
using f-strings. days = 365
The syntax is simple, just insert the variable print(f"There are {days}
in-between a set of curly braces {}.
in a year")
www.datateach.ai
PYTHON CHEAT SHEET
MATHS
Arithmetic Operators
You can do mathematical calculations with 3+2 #Add 4-1
Python as long as you know the right #Subtract 2*3
operators.
#Multiply 5/2
#Divide 5**2
#Exponent
The += Operator
This is a convenient way to modify a variable.
It takes the existing value in a variable my_number = 4
and adds to it. my_number += 2
You can also use any of the other
#result is 6
mathematical operators e.g. -= or *=
www.datateach.ai
PYTHON CHEAT SHEET
ERRORS
Syntax Error
Syntax errors happen when your code print(12 + 4))
does not make any sense to the computer. File "<stdin>", line 1
This can happen because you've misspelt
print(12 + 4))
something or there's too many brackets or
a missing comma. ^
SyntaxError: unmatched ')'
Name Error
This happens when there is a variable
with a name that the computer my_number = 4 my_Number + 2
does 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. NameError: name 'my_Number' is
Note: variable names are case sensitive!
not defined
www.datateach.ai
PYTHON CHEAT SHEET
FUNCTIONS
Creating Functions
This is the basic syntax for a function in def my_function():
Python. It allows you to give a set of print("Hello")
instructions a name, so you can trigger it
multiple times without having to re-write or name = input("Your name:")
copy-paste it. The contents of the function print("Hello")
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
the function followed by a set of round
brackets. This allows you to determine function my_function
when to trigger the function and how #will run twice.
many times.
www.datateach.ai
PYTHON CHEAT SHEET
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
a variable will determine its value. n = 3
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
When calling a function, you can provide def divide(n1, n2):
a keyword argument or simply just the result = n1 / n2
value.
Using a keyword argument means that #Option 1:
you don't have to follow any order divide(10, 5)
when providing the inputs. #Option 2:
divide(n2=5, n1=10)
www.datateach.ai
PYTHON CHEAT SHEET
CONDITIONALS
If
This is the basic syntax to test if a condition n = 5
is true. If so, the indented code will be if n > 2:
executed, if not it will be skipped.
print("Larger than 2")
Else
This is a way to specify some code that will be age = 18
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
condition, you can add extra conditions to weather = "sunny"
test if the first condition is false. if weather == "rain":
Once an elif condition is true, the rest of
print("bring umbrella")
the elif conditions are no longer checked
and are skipped. elif weather == "sunny":
print("bring sunglasses")
elif weather == "snow":
print("bring gloves")
www.datateach.ai
PYTHON CHEAT SHEET
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
This expects either of the conditions either age = 12
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
condition. e.g. if it was true then it's now if not 3 > 1:
false. print("something")
#Will not be printed.
comparison operators
These mathematical comparison operators
allow you to refine your conditional checks. > Greater than
< Lesser than
>= Greater than or equal to
<= Lesser than or equal to
== Is equal to
!= Is not equal to
www.datateach.ai
PYTHON CHEAT SHEET
LOOPS
While Loop
This is a loop that will keep repeating itself n = 1
until the while condition becomes false. while n < 100:
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 dictionary
or tuple. for fruit in all_fruits:
print(fruit)
_ in a For Loop
If the value your for loop is iterating through,
e.g. the number in the range, or the item in for _ in range(100):
the list is not needed, you can replace it with #Do something 100 times.
an underscore.
break
This keyword allows you to break free of the
loop. You can use it in a for or while loop. scores = [34, 67, 99, 105]
for s in scores:
if s > 100:
print("Invalid")
break
print(s)
www.datateach.ai
PYTHON CHEAT SHEET
continue n = 0
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. n += 1
if n % 2 == 0:
continue
print(n)
#Prints all the odd numbers
Infinite Loops
Sometimes, the condition you are checking while 5 > 1:
to see if the loop should continue never print("I'm a survivor")
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.datateach.ai
PYTHON CHEAT SHEET
LIST METHODS
List Index
To get hold of a particular item from a
list you can use its index number. letters = ["a", "b", "c"]
This number can also be negative, if you letters[0]
want to start counting from the end of the
#Result:"a"
list.
letters[-1]
#Result: "c"
List Slicing
Using the list index and the colon symbol
you can slice up a list to get only the #list[start:end]
portion you want. letters = ["a","b","c","d"]
Start is included, but end is not.
letters[1:3]
#Result: ["b", "c"]
www.datateach.ai
PYTHON CHEAT SHEET
BUILT IN FUNCTIONS
Range
Often you will want to generate a range # range(start, end, step)
of numbers. You can specify the start, end for i in range(6, 0, -2):
and step.
Start is included, but end is excluded: print(i)
start <= range < end
# result: 6, 4, 2
# 0 is not included.
Randomisation
The random functions come from the import random
random module which needs to be # randint(start, end)
imported.
In this case, the start and end are both n = random.randint(2, 5)
included #n can be 2, 3, 4 or 5.
start <= randint <= end
Round
This does a mathematical round.
So 3.1 becomes 3, 4.5 becomes 5 round(4.6)
and 5.8 becomes 6. # result 5
abs
This returns the absolute value.
Basically removing any -ve signs. abs(-4.6)
# result 4.6
www.datateach.ai
PYTHON CHEAT SHEET
MODULES
Importing
Some modules are pre-installed with python import random
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 give import random as r
your module a different name. n = r.randint(1, 5)
Importing Everything
You can use the wildcard (*) to import
everything from a module. Beware, this from random import *
usually reduces code readability. list = [1, 2, 3]
choice(list)
# More readable/understood
#random.choice(list)
www.datateach.ai
PYTHON CHEAT SHEET
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()
print(car1.colour) #black
www.datateach.ai
PYTHON CHEAT SHEET
Class Properties
You can create a variable in the init() of
a class so that all objects created from the class Car:
class has access to that variable. def __init__(self, name):
self.name = "Jimmy"
Class Inheritance
When you create a new class, you can class Animal:
inherit the methods and properties def breathe(self):
of another class.
print("breathing")
class Fish(Animal):
def breathe(self):
super().breathe()
print("underwater")
nemo = Fish()
nemo.breathe()
#Result:
#breathing
#underwater
www.datateach.ai