Show Menu
Cheatography

Python Cheat Sheet (DRAFT) by

Essential Python methods

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

Arithmetic Operators

+ Addition
print(3 + 5) # 8
- Subtra­ction
print(8 - 6) # 2
* Multip­lic­ation
print(1 + 2 + 3 * 3) # 12
/ Division
print(8 / 4) # 2
% Mod (the remainder after dividing)
print(9 % 2) # 1
** Expone­nti­ation
print(3 ** 2) # 9
// Divides and rounds down to the nearest integer
print (16 // 3) # 5

Logical Operators

and
Evaluates if all provided statements are True
5 < 3 and 5 == 5 # False
or
Evaluates if at least one of many statements is True
5 < 3 or 5 == 5 # True
not
Flips the Bool Value
not 5 < 3 # True

Data Structures

months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

print(months[0]) # January
print(months[1]) # February
print(months[7]) # August
print(months[-1]) # December
print(months[25]) # IndexError: list index out of range
 

Assignment Operators

x = 3 y= 4 z=5
x, y, z = 3, 4, 5
+= Addition Assignment
a += 1 # a = a + 1
-= Subtra­ction Assignment
a -= 3 # a = a - 3
*= Multip­lic­ation Assignment
a = 4 # a = a 4
/= Division Assignment
a /= 3 # a = a / 3
%= Remainder Assignment
a %= 10 # a = a % 10
**= Exponent Assignment
a **= 10 # a = a ** 10

Strings

my_string = 'this is a string!'
my_string2 = "this is also a string­!!!­"
this_s­tring = 'Simon\'s skateboard is in the garage.'
print(­fir­st_word + ' ' + second­_word) >> Hello There
print(­len­(fi­rst­_word)) >> 5
print(­fir­st_word * 5) >> HelloH­ell­oHe­llo­Hel­loHello
index into strings >> first_­word[0] >> H, first_­word[1] >> e
 

Comparison Operators

== Is Equal To
3 == 5 # False
!= Not Equal To
3 != 5 # True
> Greater Than
3 > 5 # False
< Less Than
3 < 5 # True
>= Greater Than or Equal To
3 >= 5 # False
<= Less Than or Equal To
3 <= 5 # True

Strings methods

len(), returns the length of an object, like a string
print(­len­("ab­aba­") / len("ab­")) >> 2.5
type(), check the data type of any variable
print(­typ­e('­Hel­lo')) >> str
'sebastian thrun'.islower()
True
'Sebastian Thrun'..count('a')
2
'Sebastian Thrun'..find('a')
3
'Sebastian Thrun'..rfind('a')
7
animal = "dog"
action = "bite"
print("Does your {} {}?".format­(an­imal, action))
Does your dog bite?
"The cow jumped over the moon.".split()
['The', 'cow', 'jumped', 'over', 'the', 'moon.']
"The cow jumped over the moon.".split(' ', 3)
['The', 'cow', 'jumped', 'over the moon.']
"The cow jumped over the moon.".split('.')
['The cow jumped over the moon', '']
"The cow jumped over the moon.".split(­None, 3)
['The', 'cow', 'jumped', 'over the moon.']