Show Menu
Cheatography

Python3 Beginner Sheet Cheat Sheet (DRAFT) by

A beginner sheet for Python3.

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Fundam­entals

my_int = 5
my_string = "­Hello World"
my_oth­er_­string = 'Hello there'
Print to console:
print(­"­Hello World!­")
Collect input (string):
my_input = input(­"­Write: ")
Addition:
5 + 3
Subtra­ction:
5 - 3
Multip­lic­ation:
5 * 3
Float division:
5 \ 3
Integer division (floors):
5 \\ 3
Modulo:
5 % 3
Expone­nti­ation:
5 ** 3
True:
True
False:
False
Type conver­sion:
str()
,
int()
,
float()
,
bool()
Detect the type:
type()
Equality of values:
a == b
Equality of refere­nces:
a is b

Condit­ional Logic

if (boolean_condition_1):
    result_1
elif (boolean_condition_2):
    result_2
else:
    result_default
If one block has been executed, the others cannot be executed, even if their relative condition is
True
.

Looping

for i in range(5):
    print(i) # Prints 0 to 4

for i in ["Alpha", "Beta"]:
    print(i) # Prints "Alpha" and "Beta"

j = 0
while (j < 3):
    print(j) # Prints 0 to 3
    j = j+1
You can loop through an iterable, which can be a range, a list, a tuple, a dictionary using
for
or through a condition, using
while
.
 

List Compre­hension

# Squares of even numbers less than 10
[i * i for i in range(10) if i % 2 == 0]

# Multiple conditions (odds become negative)
[i if i % 2 == 0 else -i for i in range(10]

List Methods

Add an item to the end:
lst.ap­pen­d(item)
Add a list of items to the end:
lst.ex­ten­d(l­ist­_of­_items)
Insert an item at an index:
lst.in­ser­t(i­ndex, item)
Remove all items:
lst.cl­ear()
Remove & return an item at an index:
lst.po­p(i­ndex)
Remove the first item with given value:
lst.re­mov­e(val)
Removes an item at an index:
lst.de­l(i­ndex)
Gives the index of a given value:
lst.in­dex­(val, start, end)
Gives the count of a given value:
lst.co­unt­(val)
In-place reverses the list:
lst.re­verse()
In-place sorts the list:
lst.sort()
String aggreg­ates: sep.jo­in(lst)
Negative indices start from the end of the list, with
my_lis­t[-1]
. Using
list()
converts an iterable to a list.

Slicing

lst = [0, 5, 10, 15, 20]
# Generic
collection[start:end:step]

collection[3] # 15
collection[1:] # [5, 10, 15, 20]
collection[:2] # [0, 5]
collection[::2] # [0, 10, 20]
collection[::-1] # [20, 15, 10, 5, 0]
Slicing can be applied to ordered collec­tions. The start is inclusive and the end is exclusive.
 

Zip

Dictionary Methods