0% found this document useful (0 votes)
94 views

Python Cheat Sheet

This document provides a cheat sheet overview of key Python concepts like variables, data types, strings, mathematical operators, functions, and errors. It explains basics like print statements, comments, and input/output as well as more advanced topics such as f-strings, scope, and keyword arguments.

Uploaded by

Abdullah zahid
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views

Python Cheat Sheet

This document provides a cheat sheet overview of key Python concepts like variables, data types, strings, mathematical operators, functions, and errors. It explains basics like print statements, comments, and input/output as well as more advanced topics such as f-strings, scope, and keyword arguments.

Uploaded by

Abdullah zahid
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

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.

The += Operator my_age = 23


This is a convenient way of saying: "take the my_age += 5
previous value and add to it. #my_age is now 28

Page 1 Aversity.com
Python Cheat Sheet
| Aversity.com

Data Types
Integers my_number = 354
Integers are whole numbers.

Floating Point Numbers


Floats are numbers with decimal places.
When you do a calculation that results in a my_float = 3.14159
fraction e.g. 4 ÷ 3 the result will always be a
floating point number.

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"

Escaping a String speech = "She said: \"Hi\""


Because the double quote is special, it denotes a print(speech)
string, if you want to use it in a string, you need to #prints: She said: "Hi"
escape it with a "\

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

Converting Data Types


You can convert a variable from one
data type to another.
Converting to float: n = 354
float() new_n = float(n)
Converting to int: int() print(new_n) #result 354.0
Converting to string: str()

Checking Data Types


You can use the type() function to n = 3.14159
check what is the data type of a type(n) #result float
particular variable.

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 *=

The Modulo Operator


Often you'll want to know what is the
remainder after a division. e.g. 4 ÷ 2 = 2
with no remainder but 5 ÷ 2 = 2 with 1
remainder The modulo does not give 5 % 2
you the result of the division, just the #result is 1
remainder. It can be really helpful in
certain situations, e.g. figuring out if a
number is odd or even.

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

Zero Division Error 5 % 0


Traceback (most recent call
This happens when you try to divide by
last): File "<stdin>", line 1,
zero, This is something that is
ZeroDivisionError: integer
mathematically impossible so Python
division or modulo by zero
will also complain.

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.

Functions with Inputs


In addition to simple functions, you
can give the function input, this way, def add(n1, n2):
each time the function can do print(n1 + n2)
something different depending on
the input. It makes your function add(2, 3)
more useful and re-usable.

Page 6 Aversity.com
Python Cheat Sheet
| Aversity.com

Functions with Outputs


In addition to inputs, a function can def add(n1, n2):
also have an output. The output return n1 + n2
value is proceeded by the keyword
"return". This allows you to store the result = add(2, 3)
result from a function.

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")

Elif weather = "sunny"


In addition to the initial If statement
if weather == "rain":
condition, you can add extra
print("bring umbrella")
conditions to test if the first
elif weather == "sunny":
condition is false. Once an elif
print("bring sunglasses")
condition is true, the rest of the elif
elif weather == "snow":
conditions are no longer checked
print("bring gloves")
and are skipped.

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.

break scores = [34, 67, 99, 105]


This keyword allows you to break free for s in scores:
of the loop. You can use it in a for or if s > 100:
while loop. print("Invalid")
break
print(s)

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

Adding an Item to a List


If you just want to add a single item all_fruits = ["apple",
to a list, you need to use the "banana", "orange"]
.append() method. all_fruits.append("pear")

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)

Importing from modules


You can import a specific thing from
a module. e.g. a from random import randint
function/class/constant You do this n = randint(1, 5)
with the from keyword. It can save
you from having to type the same
thing many times.

Importing Everything from random import *


You can use the wildcard (*) to list = [1, 2, 3]
import everything from a module. choice(list)
Beware, this usually reduces code # More readable/understood
readability. #random.choice(list)

Page 14 Aversity.com
Python Cheat Sheet
| Aversity.com

CLASSES & OBJECTS


Creating a Python Class
You create a class using the class
keyword. Note, class names in class MyClass:
Python are PascalCased. So to create #define class
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 class Car:


def drive(self):
You can create a function that
print("move")
belongs to a class, this is known as a
my_honda = Car()
method.
my_honda.drive()

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

The __init__ method


class Car:
def __init__(self):
The init method is called every time a print("Building car")
new object is created from the class. my_toyota = Car()
#You will see "building car"
#printed.

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.

Class Inheritance class Animal:


def breathe(self):
When you create a new class, you print("breathing")
can inherit the methods and class Fish(Animal):
properties of another class. def breathe(self):
super().breathe()
print("underwater")
nemo = Fish()
nemo.breathe()
#Result:
#breathing
#underwater

Page 16 Aversity.com

You might also like