Show Menu

Essential Python Cheat Sheet by

A brief Python language reference for Python 2.6+ / 3.0+.
python     functions     string     conversion     statement     boolean     tuple

Data Types

Integer
-256, 15
Float
-253.23, 1.253e-10
String
"­Hel­lo", 'Goodbye', "­"­"­Mul­til­ine­"­"­"
Boolean
True, False
List
[ value, ... ]
Tuple
( value, ... )1
Dictionary
{ key: value, ... }
Set
{ value, value, ... }2
1 Parent­heses usually optional
2 Create an empty set with set()

Statements

If Statem­ent
if expre­ssion:
 ­ ­sta­tements
elif expre­ssion:
 ­ ­sta­tements
else:
 ­ ­sta­tements

While Loop
while expre­ssion:
 ­ ­sta­tements

For Loop
for var in colle­ction:
 ­ ­sta­tements

Counting For Loop
for i in range(­st­art, end [, step]):
 ­ ­sta­tements
(start is included; end is not)

Arithmetic Operators

x + 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 Operators

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

Boolean Operators

not x
x and y
x or y

Exception Handling

try:
 ­ ­sta­tements
except [ exception type [ as var ] ]:
 ­ ­sta­tements
finally:
 ­ ­sta­tements
 

Conversion Functions

int(e­xpr)
Converts expr to integer
float(­expr)
Converts expr to float
str(e­xpr)
Converts expr to string
chr(num)
ASCII char num

String / List / Tuple Operations

len(s)
length of s
s[i]
ith item in s (0-based)
s[s­tart : 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 concat­enation of s with t
s * n
n copies of s concat­enated
sorted­(s)
a sorted copy of s
s.in­dex­(i­tem)
position in s of item

More String Operations

s.lo­wer()
lowercase copy of s
s.re­pla­ce(­old, new)
copy of s with old replaced with new
s.split( delim )
list of substrings delimited by delim
s.st­rip()
copy of s with whitespace trimmed
s.up­per()
uppercase copy of s

Mutating List Operations

del lst[i]
Deletes ith item from lst
lst.a­pp­end­(e)
Appends e to lst
lst.i­ns­ert­(i, e)
Inserts e before ith item in lst
lst.s­ort()
Sorts lst

Dictionary Operations

len(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 Defini­tions

def name­(a­rg1, arg2, ...):
 ­ ­st­ate­ments
 ­ ­return expr
 

Enviro­nment

sys.argv
List of command line arguments (argv[0] is execut­able)
os.environ
Dictionary of enviro­nment variables
os.curdir
String with path of current directory
import sys; print(­sys.ar­gv)­ ­ ­ ­ or
from sys import argv; print(­argv)

String Formatting

"­Hello, {0} {1}".fo­rma­t("a­be", "­jon­es")
Hello, abe jones

"­Hello, {fn} {ln}".f­orm­at(­fn=­"­abe­", ln="­jon­es")
Hello, abe jones

"You owe me ${0:,.2­f}­".fo­rma­t(2­534­22.3)
You owe me $253,4­22.30

now = dateti­me.n­ow()
'{:%Y-­%m-%d %H:%M:­%S}­'.f­orm­at(now)
2012-­05-16 15:04:33

Useful Functions

exit( code )
Terminate program with exit code
raw_in­put­("p­rom­pt­")
Print prompt and readline() from stdin1
1 Use input(­"­pr­omp­t") in Python 3

Code Snippets

Loop Over Sequence
for index, value in enumer­ate­(seq):
 ­ ­pri­nt(­"{} : {}".f­or­mat­(index, value))

Loop Over Dictio­nary
for key in sorted­(dict):
 ­ ­pri­nt(­dic­t[key])

Read a File
with open("f­ile­nam­e", "­r") as f:
 ­ for line in f:
 ­ ­ ­ line = line.r­str­ip(­"­\n") # Strip newline
 ­ ­ ­ ­pri­nt(­line)

Other References

Download the Essential Python Cheat Sheet

2 Pages
//media.cheatography.com/storage/thumb/sschaub_essential-python.750.jpg

PDF (recommended)

Alternative Downloads

Share This Cheat Sheet!

Like this cheat sheet? Check out our sponsors!

Readable.io is a collection of tools to make your writing better. More readable content means higher conversion rates and better reader engagement. Measure website and document readability, measure keyword density and more!

Click Here To Get Started!

 

Comments

olorinj olorinj, 07:51 22 Mar 16

Amazing cheatsheet.

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          C Reference Cheat Sheet

          More Cheat Sheets by sschaub