Python Cheatsheet
Python Cheatsheet
Cheat Sheet
Andrei Dumitrescu
This cheat sheet provides you with all the Python fundamentals in one place.
If you want to MASTER all the Python key concepts starting from Scratch, check out my Python
Complete Bootcamp course. No prior Python knowledge is required.
V1.0
TABLE OF CONTENTS
Variables
Defining variables, Comments in Python
Data Types
Python Operators
Arithmetic Operators, Assignment Operators, Arithmetic Built-in Function, Comparison and Identity
Operators, Boolean Variables, Truthiness of Objects, Boolean Operators
Python Strings
Introduction, User Input and Casting, Indexing and Slicing, Formatting Strings, String Methods
For Loops
range(), for and continue, for and break
While Loops
Python Lists
Introduction, Iterating over a list, List Membership, List Methods, List Comprehension
Python Tuples
Introduction, Iterating over a tuple, Tuple membership, Tuple Methods
Dictionaries in Python
Introduction, Dictionary Methods, Iterating, zip() Built-in Function, Dictionary Comprehension
Python Functions
Introduction, Function's Arguments, Scopes and Namespaces, Lambda Expressions
Defining variables
Comments in Python
Comments in Python start with the hash character # and extend to the end of the physical line.
If you want to comment out more lines, insert a hash character at the beginning of each line.
The following line is commented out and will be ignored by the Python Interpreter
#x=1
Data Types
# type dictionary
countries = {'de':'Germany', 'au':'Australia', 'us':'United States of America', 'gr':'Greece'}
Python Operators
Arithmetic Operators
a=9
b=4
a+b # addition operator => 13
a-b # subtraction operator => 5
a*b # multiplication operator => 36
a/b # division operator => 2.25
a // b # floor division operator => 2
5.0 // 3.0 # => 1.0 -> works on floats too
a ** b # exponentiation operator (a to the power of b) => 6561
a%b # modulus operator => 1
Assignment Operators
a=5
a += 2 # shorthand for a = a + 2 => a = 7
a -= 3 # shorthand for a = a - 3 => a = 4
a /= 2 # shorthand for a = a / 2 => a = 2
a *= 3 # shorthand for a = a * 3 => a = 6
a **=2 # shorthand for a = a ** 2 => a = 36
divmod(9, 4) # returns the quotient and the remainder using integer division => (2, 1)
sum([1,2,4]) # returns the sum of an iterable => 7
min(1,-2,3) # returns the minimum value => -2
max(1,2,4) # returns the maximum value => 4
a = 10/3 # a = 3.3333333333
round(a, 4) # returns a number rounded with 4 decimals => 3.3333
pow(2, 4) # 2 ** 4 = 16
# Assignment operator is =
a=2
b=3
# Equality operator is ==
# It compares the values stored in variables
a == b # => False
b == b # => True
# Inequality operator is !=
a != b # => True
# Other comparisons
a > b # => False
5 >= 5 # => True
b <= a # => False
id(a) # => returns the address where the value referenced by a is stored. Ex: 140464475242000
# is operator checks if two variables refer to the same object (saved at the same memory
address)
a is b # => False = compares the address of a to the address of b
# equivalent to:
id(a) == id(b)
Truthiness of objects
# expression1 and expression2 => True when both expressions are True and False otherwise
# expression1 or expression2 => True when any expression is True
a, b = 3, 5
a < 10 and b < 10 # => True
a < 10 and b > 10 # => False
# !!
# Python considers 4 > 2 and 2 == True.
4 > 2 == True # => False
(4 > 2) == True # => True
Python Strings
Introduction to Strings
Strings (str objects) are enclosed in single or double quotes (' or "). Just be consistent within your
code and don't mix up " with '
# hello1 = 'Hi there! I\'m Andrei' # => error, cannot use ' inside ' ' or " inside " "
hello1 = 'Hi there! I\'m Andrei' # => correct. ' inside ' ' must be escaped using \
hello2 = "Hi there! I'm Andrei" # you can use ' inside " " or " inside ' '
# Instructions between triple quotes (""" or ''') are treated as comments, but they are not comments
but documentation.. It's recommended to use only # for commenting individual lines
"""
This is a documentation (treated as a comment)
a=5
print(a)
Comment ends here.
"""
# \n is a new line
print('Hello \nWorld!') # => it displays Hello World! on 2 lines
Formatting Strings
price = 1.33
quantity = 5
'The price is {} and the total value is {}'.format(price, price * quantity) # => 'The price is 1.33 and
the total value is 6.65'
'The price is {0} and the total value is {1}'.format(price, price * quantity) # => 'The price is 1.33
and the total value is 6.65'
'The total value is {1} and the price is {0}'.format(price, price * quantity) # => 'The total value is
6.65 and the price is 1.33'
print('The total value is ', price * quantity) # => 'The total value is 6.65'
String Methods
# All string methods return a new string but don't modify the original one
my_str = 'I learn Python Programming'
my_ip = '$$$10.0.0.1$$'
my_ip.strip('$') # => '10.0.0.1'
# str.find() returns the first index in my_str where substring 'is' is found or -1 if it didn't find the
substring
my_str.find('is') # => 2
my_str.find('xx') # => -1
Syntax
a, b = 3, 5
# if a is less that b execute the indented block of code under the if clause, otherwise go and test
the elif condition
if a < b:
print('a is less than b')
elif a == b:
print('a is equal to b')
else:
print('a is greater than b')
or / and operators
your_age = 14
a=3
if 1 < a <= 9:
print('a is greater than 1 and less than or equal to 9')
# equivalent to:
if a > 1 and a <= 9:
print('a is greater than 1 and less than or equal to 9')
# 2nd example - and operator. It returns True if both expressions are True, False otherwise
if a % 2 == 0 and a % 3 == 0:
print('Example 2: a is divisible by 2 and 3 (or by 6)')
# 3rd example
if not (a % 2 and a % 3 ):
print('Example 2: a is divisible by 2 and 3 (or by 6)')
b=0
if b: # it tests the truthiness of b or bool(b)
print('The truthiness of b is True')
else:
print('The truthiness of b is False')
name = 'Andrei'
# Pythonic version
print('Hello Andrei') if name == 'Andrei' else print('You are not Andrei!')
# equivalent to:
if name == 'Andrei':
print('Hello Andrei')
else:
print('You are not Andrei')
For Loops
It iterates over a sequence and executes the code indented under the for clause for each element
in the sequence
movies = ['Star Wars', 'The Godfather', 'Harry Potter ', 'Lord of the Rings']
for m in movies:
print(f'One of my favorites movie is {m}')
else: #the code below gets executed when "for" has finished looping over the entire list
print('This is the end of the list')
range()
for i in range(100):
pass # => empty instruction or "do nothing"
for i in range (8, -4, -2): # => from 8 included to -4 excluded in steps of -2
print(i, end=' ')
# it prints: 8 6 4 2 0 -2
# for ... continue -> it prints out all letters of the string without 'o'
for letter in 'Python Go and Java Cobol':
if letter == 'o':
continue # go to the beginning of the for loop and do the next iteration
print(letter, end='')
a = 10
print('Loop ended.')
Python Lists
# Creating lists
list1 = [] # empty list
list2 = list() # empty list
list3 = list('Python') # => ['P', 'y', 't', 'h', 'o', 'n'] -> creates a list from a string
list4 = ['Python', 'Go', 2018, 4.5, [1,2.3, 'abc']] # a list stores any type of object
len(list4) # => 5 -> returns the number of elements in the list
l1 = [1, 2, 3]
l2 = l1 # l1 and l2 reference the same object, l2 IS NOT a copy of l1
l1 is l2 # => True
l1 == l2 # => True
l1.append(4) # here I've modified both l1 and l2, they are still the same list
l1 is l2 # => True
l1 == l2 # => True
l1 = [1, 2]
id(l1) # => 139875652516360 (you'll get another value)
l1 += [3, 4] # => [1, 2, 3, 4] -> concatenating a new list to l1 - equivalent to using extend()
id(l1) # => 139875652516360 -> it's the same list
List Membership
in and not in operators test list membership
'10.0.0.1' in ip_list # => returns True
'192' not in ip_list # => returns True
'192' in ip_list # => returns False
List Methods
# list.remove() removes the first occurance and doesn't return an item of the list
print(list1) #[1, 2.2, 'abc', 5, [6, 7], 5.2, 'x', 'y']
list1.remove('abc') # => [1, 2.2, 5, [6, 7], 5.2, 'x', 'y']
#list1.remove('a') # ValueError: list.remove(x): x not in list
# Sort a list
# list.sort() and sorted(list)
nums = [6, -1, 55, 2.3]
sorted(nums) # => [-1, 2.3, 6, 55] -> returns a NEW sorted list
print(nums) # => [6, -1, 55, 2.3]
List Comprehension
s = [x for x in range(10)]
print(s) # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
evens = [x for x in s if x % 2 == 0]
print(evens) # => [0, 2, 4, 6, 8]
# Celsius to Fahrenheit
celsius = [7.12, 10.1, 14.15, 22.5, 29.4, 32.9]
fahrenheit = [ 1.8 * x + 32 for x in celsius ]
print(fahrenheit) # => [44.816, 50.18, 57.47, 72.5, 84.92, 91.22]
Python Tuples
# Creating tuples
t0 = () # empty tuple
t1 = tuple() # empty tuple
t = (1.2) # this isn't a tuple, it's a float!
type(t) # => float
t2 = (1.2,) # creating a tuple with a single element (comma is mandatory)
t3 = tuple('abc') # creating a tuple from an iterable (string)
t4 = tuple([1, 3.2, 'abc']) # creating a tuple from an iterable (list)
t5 = (1, 3.2, 'abc')
Tuple membership
in and not in operators test tuple membership
'The Legend' in movies # => True
'The Legend' not in movies # => False
# Sorting tuples
# tuple.sort() and sorted(tuple)
nums = (6, -1, 55, 2.3)
sorted(nums) # => (-1, 2.3, 6, 55) -> returns a new sorted list
max(nums) # => 55
min(nums) # => -1
sum(nums) # => 62.3
Introduction to sets
# Creating sets
set1 = set() # empty set
#x = {} # x is a dictionary, not a set
set2 = {'a', 1, 2, 1, 'a', 2.3, 'a'} # => {1, 2, 2.3, 'a'} -> unique unordered collection
set3 = set('hellooo python') # =>{'n', 'e', 'p', 't', 'o', 'h', 'l', ' ', 'y'}
set4 = set([1, 2.3, 1, 'a', 'a', 2.3, 'b', 5]) # => {1, 2.3, 5, 'a', 'b'}
#set4[0] # TypeError: 'set' object does not support indexing
set5 = {(1, 2), 'a'} # a set can contain immutable objects like tuples
#set6 = {[1, 2], 'a'} # TypeError: unhashable type: 'list' -> list is mutable, not allowed in set
s1 = {1, 2, 3}
s2 = {3, 1, 2}
s1 == s2 # => True - order does not matter
some_letters = set('abcabc')
for letter in some_letters: # prints: c a b
print(letter, end=' ')
Set Membership
Set Methods
# set.copy() creates a copy of the set (not a reference to the same object)
s4 = s1.copy()
s4 is s1 # => False
s4 == s1 # => True
s4.add('z')
s4 == s1 # => False
s1 = {1, 2, 3, 'x'}
# set.pop() removes and returns an arbitrary set element
item = s1.pop()
print(f'item:{item}, s1:{s1}') # => item:1, s1:{2, 3, 'x'}
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# set.difference() returns the set of elements that exist only in set1 but not in set2
set1.difference(set2) # => {1, 2}
set1 - set2 # => {1, 2}
# set.symetric_difference() returns the set of elements which are in either of the sets but not in
both
set1.symmetric_difference(set2) # => {1, 2, 4, 5}
set1 ^ set2 # => {1, 2, 4, 5}
# set.union() returns the set of all unique elements present in all the sets
set1.union(set2) # => {1, 2, 3, 4, 5}
set1 | set2 # => {1, 2, 3, 4, 5}
# set.intersection() returns the set that contains the elements that exist in both sets
set1.intersection(set2) # => {3}
set1 & set2 # => {3}
# All set methods that don't modify the set are available to frozensets
fs1 & set2 # => frozenset({3})
Dictionaries in Python
Introduction to dictionaries
# Creating dictionaries
dict1 = {} # empty dictionary
dict2 = dict() # empty dictionary
# dict.get() supports a default argument which is returned when the key is missing
product.get("id", 4) # => 1234
product.get("review", 'N/A') # => 'N/A'
# dict.pop() removes the specified key and returns the corresponding value.
# If key is not found, a default value is given, otherwise KeyError is raised
name = product.pop('name') # name is 'Laptop'
print(product) # => {'id': 1234, 'price': 888.99}
# name = product.pop('name') # => KeyError: 'name', key 'name' doesn't exist anymore
name = product.pop('name', 'No such key') # => name is 'No such key'
#equivalent to:
for k in product.keys():
print(f'key:{k}')
# Zipping in a dictionary
sales_dict = dict(zip(years, sales))
print(sales_dict) # => {2015: 20000, 2016: 30000, 2017: 40000, 2018: 45000}
## Doubled values
d2 = {k: v * 2 for k, v in d1.items()}
print(d2) # => {'a': 2, 'b': 4, 'c': 6}
Python Functions
Introduction to Functions
Function's Arguments
# wrong way to define a function => SyntaxError: non-default argument follows default argument
# def my_function(a, b=5, c):
# print(a, b, c)
def my_func1():
print(f'x is {x}') # this is "x" from the global namespace
def my_func2():
x=6 # this is a local scoped variable
print(f'x is {x}') # this is NOT "x" from the global namespace
def my_func4():
print(f'x is {x}')
x += 7 # this is an error, we used local x before assignment
Lambda Expressions
## Open the file in read-only mode and reads its contents as a list
## the file object will be automatically closed
with open('a.txt', 'r') as my_file:
content = my_file.readlines() # content is a list
Exceptions Handling
a=2
# for ZeroDivisionError
b=0
# for TypeError
b = '0'
try:
# Try to execute this block of code!
c=a/b
print(c)
except ZeroDivisionError as e:
# This block of code is executed when a ZeroDivisionError occurs
# this is de destructor, it's automatically called then the object gets out of scope
# MOST of the time it's not recommended to implement it (Python has a garbage collector)
def __del__(self):
# print('Robot died')
pass
def __add__(self, other): # magic method, called automatically when adding 2 objects
return self.energy + other.energy
print(Robot.population) # => 2
print(r1.population) # => 2