Show Menu
Cheatography

python basics Cheat Sheet (DRAFT) by

A brief reference sheet for Python.

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

Variable Assignment

tempor­arily store data
x = 5
 
x = 'one'

Calcul­ations :

sum
y = x+2
Subtra­ction
y = x-2
Multip­lic­ation
y = x * 2
Expone­nti­ation
y = x ** 2
Remainder
y = x % 2
Division
y = x/2

Comparison Operators

x< y
Less
x <= y
Less or eq
x > y
Greater
x >= y
Greater or eq
x == y
Equal
x != y
Not equal

Type Conversion

str()
'5', '3.45', 'True'
int()
5, 3, 1
float()
5.0, 1.0
bool()
True, True, False

string methods

my_str­ing.up­per()
String to uppercase
my_str­ing.lo­wer()
String to lowercase
my_str­ing.co­unt­('w')
Count String elements
my_str­ing.re­pla­ce('e', 'i')
Replace String elements
my_str­ing.st­rip()
Strip whites­paces
 

functions

def user(name):
    print(”Hi {name}”)



user(“n”)

string

my_string = 'thisS­tring'
my_string * 2
'thisS­tri­ngt­his­String'
>>> my_string + 'isnew'
'thisS­tri­ngI­snew'
't' in my_string
True

lists

Lists numbers = [1, 2, 3, 4, 5]
numbers[0]
returns the first item

lists

number­s.a­ppe­nd(6)
# adds 6 to the end
number­s.r­emo­ve(6)
# removes 6
number­s.i­nse­rt(0, 6)
# adds 6 at index position of 0
number­s.pop()
# removes the last item
number­s.c­lear()
# removes all the items
number­s.i­ndex(8)
# returns the index of first occurrence of 8
number­s.s­ort()
# sorts the list
number­s.c­opy()
# returns a copy of the list
number­s.r­eve­rse()
# reverses the list
 

Statements

If Statement
if expression:
  statements
elif expression:
   statements
else:
  statements


While Loop
while expression:
  statements

For Loop
for var in collection:
  statements

Counting For Loop
for i in range(start, end [, step]):
   statements

Exception Handling

try:
  statements
except [ exception type [ as var ] ]:
  statements
finally:
  statements