Data TypesInteger | -256, 15 | Float | -253.23, 1.253e-10 | String | "Hello", 'Goodbye', """Multiline""" | Boolean | True, False | List | [ value, ... ] | Tuple | ( value, ... )1 | Dictionary | { key: value, ... } | Set | { value, value, ... }2 |
1 Parentheses usually optional
2 Create an empty set with set()
StatementsIf 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
(start is included; end is not) |
Arithmetic Operatorsx + y | add | x - y | subtract | x * y | multiply | x / y | divide | x % y | modulus | x ** y | xy |
Assignment shortcuts: x op= y
Example: x += 1 increments x
Comparison Operatorsx< y | Less | x <= y | Less or eq | x > y | Greater | x >= y | Greater or eq | x == y | Equal | x != y | Not equal |
Exception Handlingtry:
statements
except [ exception type [ as var ] ]:
statements
finally:
statements |
| | Conversion Functionsint(expr) | Converts expr to integer | float(expr) | Converts expr to float | str(expr) | Converts expr to string | chr(num) | ASCII char num |
String / List / Tuple Operationslen(s) | length of s | s[i] | ith item in s (0-based) | s[start : end] | slice of s from start (included) to end (excluded) | x in s | True if x is contained in s | x not in s | True if x is not contained in s | s + t | the concatenation of s with t | s * n | n copies of s concatenated | sorted(s) | a sorted copy of s | s.index(item) | position in s of item |
More String Operationss.lower() | lowercase copy of s | s.replace(old, new) | copy of s with old replaced with new | s.split( delim ) | list of substrings delimited by delim | s.strip() | copy of s with whitespace trimmed | s.upper() | uppercase copy of s |
Mutating List Operationsdel lst[i] | Deletes ith item from lst | lst.append(e) | Appends e to lst | lst.insert(i, e) | Inserts e before ith item in lst | lst.sort() | Sorts lst |
Dictionary Operationslen(d) | Number of items in d | del d[key] | Removes key from d | key in d | True if d contains key | d.keys() | Returns a list of keys in d |
Function Definitionsdef name(arg1, arg2, ...):
statements
return expr |
| | Environmentsys.argv | List of command line arguments (argv[0] is executable) | os.environ | Dictionary of environment variables | os.curdir | String with path of current directory |
import sys; print(sys.argv) or
from sys import argv; print(argv)
String Formatting"Hello, {0} {1}".format("abe", "jones")
Hello, abe jones
"Hello, {fn} {ln}".format(fn="abe", ln="jones")
Hello, abe jones
"You owe me ${0:,.2f}".format(253422.3)
You owe me $253,422.30
now = datetime.now()
'{:%Y-%m-%d %H:%M:%S}'.format(now)
2012-05-16 15:04:33 |
Useful Functionsexit( code ) | Terminate program with exit code | raw_input("prompt") | Print prompt and readline() from stdin1 |
1 Use input("prompt") in Python 3
Code SnippetsLoop Over Sequence
for index, value in enumerate(seq):
print("{} : {}".format(index, value))
Loop Over Dictionary
for key in sorted(dict):
print(dict[key])
Read a File
with open("filename", "r") as f:
for line in f:
line = line.rstrip("\n") # Strip newline
print(line) |
|
Created By
Metadata
Favourited By
and 56 more ...
Comments
Amazing cheatsheet.
Add a Comment
More Cheat Sheets by sschaub