Cheatography
https://cheatography.com
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
temporarily store data |
x = 5 |
|
x = 'one' |
Calculations :
sum |
y = x+2 |
Subtraction |
y = x-2 |
Multiplication |
y = x * 2 |
Exponentiation |
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_string.upper() |
String to uppercase |
my_string.lower() |
String to lowercase |
my_string.count('w') |
Count String elements |
my_string.replace('e', 'i') |
Replace String elements |
my_string.strip() |
Strip whitespaces |
|
|
functions
def user(name):
print(”Hi {name}”)
user(“n”)
|
string
my_string = 'thisString' |
my_string * 2 |
'thisStringthisString' |
>>> my_string + 'isnew' |
'thisStringIsnew' |
't' in my_string |
True |
lists
Lists numbers = [1, 2, 3, 4, 5] |
numbers[0] |
returns the first item |
lists
numbers.append(6) |
# adds 6 to the end |
numbers.remove(6) |
# removes 6 |
numbers.insert(0, 6) |
# adds 6 at index position of 0 |
numbers.pop() |
# removes the last item |
numbers.clear() |
# removes all the items |
numbers.index(8) |
# returns the index of first occurrence of 8 |
numbers.sort() |
# sorts the list |
numbers.copy() |
# returns a copy of the list |
numbers.reverse() |
# 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
|
|