Show Menu
Cheatography

python Cheat Sheet (DRAFT) by

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

Variables & Data Types

valid charac­ters:
_ [a-z] [A-Z] [0-9]
must start with:
_ [a-z] [A-Z]
integer:
-2, 0, 200
float:
3.1415, -2.68
string:
'a message'
boolean:
True, False
list:
[value0, value1, value2, ...]
dictio­nary:
{key1: value1, key2: value2, ...}
variable assign­ment:
var_name = data

List Functions

length of list:
len(list_name)
total sum of list:
sum(list_name)
minimum value in list:
min(list_name)
maximum value in list:
max(list_name)
add value to end of list:
list_name.append(value)
index access:
list_name[index­_nu­mber]

Dictionary Functions

key lookup:
dict[key]
storin­g/u­pdating key, value:
dict[key] = value
list of keys:
list(dict.keys())
list of values:
list(dict.values())
 

Comparison / Condit­ional Expression

equal:
==
not equal:
!=
less than:
<
less or equal:
<=
greater than:
>
greater or equal:
>=
equal to multiple values:
var_name in [value0, value1, value2, ...]

Miscel­laneous Functions

printing:
print(value0, value1, ...)
get input:
input('hint message')
convert to integer:
int(value)
convert to float:
float(value)
round a number:
round(value, decima­l_p­oints)

Plotting a Bar Chart

import matplotlib.pyplot as plt
%matplotlib inline

x = [1, 2, 3, 4, 5]
values = [20, 34, 12, 48]

plt.bar(x, values, align='center')

plt.xticks(x, [label1, label2, label3, label4, label5])

Defining and Calling a Function

def function_name(input1, input2):
    function's internal logic
    return result

-----------------------------------------------

var1 = data1
var2 = data2
returned_value = function_name(var1, var2)
 

If Statement / Making a Choice

if:
    block of code when cond is True
-----------------------------------------------

if cond:
    block of code when cond is True
else:
    block of code when cond is False

-----------------------------------------------

if condition1:
    block of code when condition1 is True
elif condition2:
    block of code when condition1 is
    False and condition2 is True
elif condition3:
    block of code when condition1 and
    condition2 are False and condition3 is True
else:
    block of code when condition1 and
    condition2 and condition3 are False

Loops / Iterating

Repeat n Times:
for var_name in range(n):
    block of code

Iterate Over List Values:
for var_name in list_name:
    block of code

Iterate Until Condition Becomes False:
while condition:
    repeat until condition becomes False

Filtering Data

list_of_data = [value0, value1, value2, ...]
filtered_data = []

for value in list_of_data:
    if filtering_condition:
        filtered_data.append(value)