Show Menu
Cheatography

Python (Basics) Cheat Sheet (DRAFT) by

Python Reference Card created for a basic tutorial on Python Programming. Biased towards scientific computing

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

Built-In data types

None
NoneType
None object
bool
Boolean
True, False
int
Integer
-2, -1, 0, 1, 2
long
Long Integer
123456­789­012345L
float
Floating point
3.1415
complex
complex
3 + 4*1j
str
String
'alice', 'bob'
unicode
Unicode String
u'alice', u'bob'
list
List
[1, 'two', 3.0]
tuple
Tuple
(1, 'two', 3.0)
dict
Dictionary
{'name': alice, 'age': 7}

Indent­ation matters

if Cheshire.is_visible:
    print('I can see you')
    alice.talks()
else:
    print("I can't see you")
Four spaces is the recomm­ended by PEP 8 (Style Guide for Python Code)

String Literals

'alice'
"bob"
"The Hatter's Tea"
"""Twinkle, twinkle, little bat!
How I wonder what you're at!"""

String Methods

s.lower()
Lowercased copy
s.upper()
Uppercased copy
s.isal­pha()
True if alphabetic
s.isal­num()
True if alphan­umeric
s.split(t)
Split s using t as separator
s.zfill(w)
Padding with leading zeros
s.strip()
Removes beg/end spaces
 

Lists

lst.ap­pend(x)
Append x to the end of lst
lst.co­unt(x)
How many times x is in lst
lst.ex­ten­d(itr) Same as lst += itr
Append all of iterable itr to lst
lst.in­dex(x)
Index position of the first occurrence
lst.in­ser­t(i,x)
Insert item x into lst at index i
lst.pop()
Removes the last item in lst
lst.pop(i)
Removes item with index i
lst.re­move(x)
Removes the first occurrence of x in lst
lst.re­verse()
Reverse the list lst in-place
lst.sort()
Sorts lst in-place

List Compre­hen­sions

>>> [2**x for x in range(10)]
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

>>> [2**x for x in range(10) if x%2 == 0]
 [1, 4, 16, 64, 256]

Dictio­naries

d.clear()
All items from dict d
d.copy()
Shallow copy of dict d
d.keys()
Read-only iterable of all keys
d.values()
Read-only iterable of all values
d.items()
Read-only iterable of all (key, value)
d.pop(k)
Removes (k, value) and returns d[k]

Condit­ionals

if x > 0 and y > 0:
    print('First Quadrant')
elif x < 0 and y > 0:
    print('Second Quadrant')
elif y < 0:
    print('Third and Fourth')
else:
    print('On the axis')

Loops (for)

a=1
b=2
for i in range(10):
    c=a+b
    print c
    a=b; b=c

Loops (while)

import random
x=1.0
while True:
    x*=random.random()
    print x
    if x<0.5:
        x*=3
        continue
    if x>0.8:
        break
You can use 'break' to escape from the inner loop and 'continue' to jump to the next item in the loop

Classes

class Quaternion(object):

    def __init__(self, four_tuple):
        self.values=four_tuple

    @property
    def real(self):
        return self.values[0]

Special Methods

__bool­__(­self)
True of False return
__init­__(­self, args)
Object Initia­liz­ation
__hash­__(­self)
To be use as key
__repr­__(­self)
String eval(r­epr­(x))==x
__str_­_(self)
Human readable string

Comparison Special Methods

__lt__­­(self, other)
<
__le__­­(self, other)
<=
__gt__­­(self, other)
>
__ge__­­(self, other)
>=
__eq__­­(self, other)
==
__ne__­­(self, other)
!=
 

os Module

os.lis­tdi­r(path)
Equivalent to 'ls'
os.get­cwd()
Current Working Directory (pwd)
os.mkd­ir(­path)
Make directory (mkdir)
os.chd­ir(­path)
Change directory (cd)
os.pat­h.i­sfi­le(­path)
Check if path is a file
os.pat­h.i­sdi­r(path)
Check if path is directory
os.pat­h.e­xis­ts(­path)
Check existence as file or directory

sys Module

sys.argv
List of arguments
sys.ve­rsion
Python version
sys.pl­atform
OS platform
sys.maxint
Max integer
sys.stdout
Standard output
sys.stderr
Standard error

itertools Module

produc­t('­ABCD', repeat=2)
AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD
permut­ati­ons­('A­BCD', 2)
AB AC AD BA BC BD CA CB CD DA DB DC
combin­ati­ons­('A­BCD', 2)
AB AC AD BC BD CD
combin­ati­ons­_wi­th_­rep­lac­eme­nt(­'ABCD', 2)
AA AB AC AD BB BC BD CC CD DD

math Module

sin, cos, tan
Trigon­ome­trical
asin, acos, atan
Inv. Trigon­ome­trical
sinh, cosh, tanh
Hyperbolic
asinh, acosh, atanh
Inverse Hyperbolic
ceil, floor, trunc
Truncation
log, log10
Logarithms
sqrt, exp, pow
Expone­ntials
degrees, radians
Angular conversion
pi, e
Math Constants

json Module

>>> import json
>>> dic={'name':'Alice', 'age': 7.5}
>>> dic_json=json.dumps(dic,
                     sort_keys=True,
                     indent=4, 
                     separators=(',', ': '))
>>> print dic_json
{
    "age": 7.5,
    "name": "Alice"
}
>>> dic2=json.loads(dic)
>>> dic2
 {u'age': 7.5, u'name': u'Alice'}