Download Python 2.X Cheatsheet & Reference Guide

Indentation: tab: 4 spaces – nothing more, nothing less./ dont mix spaces with tab. Python is very specific about indentation.

Comment: # a single line comment, “”” a multiline comment – in 3 quotes””

Case Sensitivity: Letter case matters in Python. ‘foo’ & ‘Foo’ are different variables.

Quotes: You can use single quotes between double quote and double quotes within single quotes interchangeably. Within triple quotes – you can use both single & double quotes.

Assert Statement – assert expression [, message]

Class and Function Decorator: @decorator

Escape codes

\n  newline
\t Horizontal tab
\\ Backslash (\) \v Vertical tab
\’ Single quote (‘)
\” Double quote (“)
\b Backspace \xhh Hex (at most 2 digits)
\f Formfeed \ooo Octal (up to 3 digits)
\n Linefeed \0 Null (not end of string)
\r Carriage return \other Not an escape

Arithmetical Operators: + plus, – minus, * multiply, /divide, % modulo, ** to the power, < less-than, > greater-than, <= less-than-equal, >= greater-than-equal, != not equal, is= object identity, is not = negated object identity

Data Types:

Boolean: passed = True, failed = False,
String: foo = ‘food without d’, i = “a”, j = ‘B’, k = “B’s Ball”, m = “C’s cat”
Int: num = 21, size = 167
Float: pi = 3.1417, avg = -21.555
Dictionary: Rollnos = {‘James’: 05, ‘Jack’: 06, ‘John’: 84}
List []: Toread = [“Chapter1”, 9, ’10’, 5.5]
Tuple(): oddnum = (3, 5, “seven”, “nine”)
NoneType: python returns this type – when there is nothing to return from a function

Python does not require an explicit declaration of the variable type. However should you need to do it, use the format:

x= float(x) # for declaring the variable as float

Variables in a String for different data types: %s – string variables, %d – decimal, %f – float.

Reserved Keywords
For python reserved keywords, use the command

from keyword import *
print kwlist

Python has 31 reserved keywords, which are:

['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import',
'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try',
'while', 'with', 'yield']


i = raw_input("Enter a string: ")
print i # raw_input always evaluates input as a string
j = input("Enter a numerical expression: ")
print j  # input evaluates any valid python type.

Output Formatting

(name = "John", age = 85, weight = 45.4)
print "The age of %s is %d and he weighs %f pounds" % (name, age, weight)

Basic Python Logic

Boolean Operators: ‘and’, ‘or’ & ‘not’ – examples: x or y, x and y, not x.

not has a lower priority than non-Boolean operators. Thus, not x == y is interpreted as not (x == y), and x == not y gives a syntax error.

Increment Operator: x= x+1 or count += 1
Other Allowed operators: -=, *=, /=, and %=:

Conditional Statements

if condition:
#do stuff if test is true
elif condition2:
#do stuff if test2 is true
else: #do stuff if both tests are false

while <condition>:

for x in range (start, stop, step)

Python Strings Manipulation

While you can manipulate the strings, strings are essentially immutable – you cannot change a part of the string. The best one can do is to create a new string as a variation on the original string.

foo = "holy cow" # string creation using single or double quotes
print foo[5]  # returns 'c' / Rem: All indexing starts at 0.
print foo[2:5]# slicing returns 'ly c'
print foo[:5]# returns 0 to 5th carecters
print foo[5:]# returns 5th to end
print foo.split(' ') # returns  ['holy', 'cow']
print foo.split('y”) # returns ['hol', 'cow']

String Formatting

%s //String
%r //also used for string
%c //Character (int or str)
%d //Decimal (base 10 integer) 
%f //Floating-point decimal
%i //Integer
%o //Octal 
%x //Hex

For a Complete list of string manipulation methods available in Python type:

You can see detailed help on strings using statements like help(str) or help (str.upper)

String Comparison

Python allows for string comparison with operators like <, >, == and !=. For example:

word = raw_input ("enter a word")
if word < "mango":
print "%s comes before mango in the dictionary." % word
elif word > "mango":
print "%s comes after mango in the dictionary." % word

Remember that python handles upper and lowercase letters differently and upper case letters come before lower lace letters. So if you enter ZEBRA or Zebra, it will come before mango.

To address this, you can convert input strings to a standard format, such as all lowercase,before performing the comparison.

Other String methods

mystrng = "Some String"
mystrng.capitalize(), [, fill])
mystrng.count(sub [, start [, end]])
mystrng.encode([encoding [,errors]])
mystrng.endswith(suffix [, start [, end]])
mystrng.format(fmtstr, *args, **kwargs)
mystrng.ljust(width [, fill])
mystrng.maketrans(x[, y[, z]])
mystrng.replace(old, new [, count])
mystrng.rjust(width [, fill])
mystrng.rsplit([sep[, maxsplit]])
mystrng.split([sep [,maxsplit]])
mystrng.startswith(prefix [, start [, end]])

File Handling

open(“C:/mydir/myfile.txt”) # open read only file. use forward slash
open(“C:/mydir/myfile.txt”, 'w') # open file with write permission # read the contents of myfile
myfile.readline() # reads the complete file into a single string
myfile.replace('Me', 'You') # replace word 'me' with 'you' in myfile
myfile.close() # close a file

Handling Directories

For assessing files in directories other than the present working directory – specify the complete file path using forward slash (/).

For accessing the current working directory, use the os module.

import os
os.getcwd() # returns the current directory
os.path.expanduser("˜") # returns the home directory
os.chdir (/someother directory)# change directory path

Inbuilt functions for examining a character or string

foo.isupper() % #returns true if is upper case
foo.islower() % #returns true if is lower case
foo.isalpha() % # returns true if a string is alphabetical
foo.isdigit() % # returns true if a string is numeric
foo.isalnum() % # returns true if is alpha-numeric
foo.isspace() % # returns true if foo is whitespace
foo.istitle() % # returns true if first letter is capitalised

Python List

A ‘list’ is an ordered set of ‘elements’, where each element is identified by an ‘index’. An expression enclosed in square brackets [] returns a new list.

mylist = [555,'love' ,'u',5.55] # creates a new list
mylist = range(1, 5) # returns the list [1, 2, 3, 4]
mylist= range(1, 10, 2) # returns [1, 3, 5, 7, 9]
mylist= list("who am i") # returns ['w','h', 'o','a', 'm','i']
foo = mylist.split() # returns ['who','am','i']
mylist = range(10, 1, -2)# returns [10, 8, 6, 4, 2]
print mylist[1] #returns 'love'
print mylist[1:3] #returns ['love' ,'u', 5.55] - slicing operation
print mylist[2:] #returns [''u', 5.55]
print mylist[2:-1]# returns ['love', 'u']
print len(mylist)# returns 4
print mylist.sort() # sorts the list in alphabetical order
mylist.append(16) # appends 16 to the list
mylist.insert(3, 'go') # inserts string "go" at the third index
mylist.remove('love') # removes 'love'
mylist.del(1) # deletes 'love'
mylist + ['hate'] # returns [555,'love' ,'u',5.55, hate ] + for concatenation
print mylist*2 # prints the list twice
mylist.find (5.55) # returns true
list2 = list1 = [555,'love' ,'u',5.55] # aliasing - no new list is formed
list3 =list1[:]# cloning of list 2 - a new list is formed in namespace

Other important charecteristics of Python Lists:

1 )Lists are mutable (i;e you can change its elements)
2) A list can appear as an element within another list (nested list)
3) Passing a list as an argument only passes a reference to the list, not a copy of the list.
4) List can be used to represent a matrix. For example, a matrix

a b c
d e f
g h i

can be represented as: mymatrix = [[a,b,c], [d, e, f], [g, h,i]]

Other list operators

mylist = [a,b,c,d,e]
mylist.append(x) // inserts object x at the end of mylist
mylist.extend(x) // Inserts each item in any iterable x at the end of mylist 
mylist.sort(key=None, reverse=False)
mylist.sort(key=str.lower, reverse=True)
mylist.reverse() // Reverses items place in mylist 
mylist.index(x [, i [, j]]) // Returns the index of the first occurrence of object x in mylist
mylist.insert(i, x) // Inserts object x into mylist at offset i
mylist.count(x) // returns the number of occurrences of x in mylist.
mylist.remove(x) // Deletes the first occurrence of object x from mylist;
mylist.pop([i]) // Deletes and returns the last (or offset i) item in mylist. Used with 
mylist.append to implement stacks. 
del mylist[i]; 

Python Tuples

A tuple consists of a number of values separated by commas. Unlike lists, these are not mutable.

mytup = () # creates an empty tuple
mytup = ('hello',) # creates a single item tuple - note the coma at the end
mytup = (4,5.5,"who" "am", 1) # creates a tuple with multiple items
mytup[3] # returns "am"
mytup[1:3] # returns (5.5,'who') - slicing
mytup = ("no",) + tup[1:] # returns ("no", 4,5.5,"who" "am", 1)
# note that we are not modifying the tuple (they are immutable).
# We are simply replacing it with a new tuple.

Use tuples when you want:
a) to represent a fixed (not changing) point in two-dimensions
b) a sequence that does not change
c) to return multiple values for a given pure function

Python Dictionaries

A dictionary is a data types used in Python for mapping a a set of key:value pairs. All keys in a dictionary must be unique.
Dictionaries are created by enclosing them in paranthesis (curly brackets {})

mydict = {} # creates an empty dictionary
mydict = {'A':1, 'B':49 , 'D': "hmm"} # creates a dictionary with key:value pairs
print len(mydict) # returns 3 - the number of key:value pairs
print mydict['B'] # returns 49
mydict.keys() # returns ['A', 'B', 'D']
mydict.values() # returns [1, 49, 'hmm']
mydict.items() # returns [('A',1), ('B',49), ('D',"hmm") ]
mydict.has_key('hmm') # returns true
'D' in mydict # returns True
'aah' in mydict # returns False
del mydict['D'] # deletes the 'D': "hmm" pair from dictionary

Other Dictionary Operators

mydict.keys() //return sll keys in mydict.
mydict.values() // return all stored values in mydict. 
mydict.items() // returns key, value pair
mydict.clear() // removes all items from mydict.
mydict.copy() // shallow copy of mydict.
mydict1.update(mydict2) // merges all of mydict2’s entries into mydict1
mydict.get(key [, default]) // returns default (or None if no default) 
mydict.setdefault(key, [, default])
mydict.popitem() // removes and returns an arbitrary (key, value) pair.
mydict.pop(k [, default]) // removes and returns mydict[k] 
mydict.has_key(k) // returns True if mydict has a key k
mydict.iteritems(), mydict.iterkeys(), mydict.itervalues() // Returns an iterator over key/value pairs, keys only, or values only. 

Python Function Definitions

def my-func(param1, param 2..):
“”” You can define what this function does in triple quotes.
This can be assessed later by calling my_func.__doc___”””

....# function code in tabbed indentation. "...." means tabbed indentation
....return foo

If a function does not return any value, python returns ‘None’

Scope of a Function

To use a function/class/module in the global scope, import it in the global scope. If imported inside a function – its definitions are not available outside the function. If you need a import to have a global scope – its a good idea to place it at the very top of your script.

Python Built-in Functions

Built-in Functions
abs() dir() hex() next() slice()
all() divmod() id() object() sorted()
any() enumerate() input() oct() staticmethod()
ascii() eval() int() open() str()
bin() exec() isinstance() ord() sum()
bool() filter() issubclass() pow() super()
bytearray() float() iter() print() tuple()
bytes() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()  
delattr() hash() memoryview() set()  
dict() help() min() setattr()  

Functions to modify type of an object

The following functions are used to modify type of an object:
● int(), long(), float(), complex()
● str(), unicode(), basestring()
● list(), tuple()
● dict()
● bool()
● set(), frozenset()
● object()


mystring.find(sub, [, start [, end]]) //returns the index of first occurence
mystrng.rfind(sub, [, start [, end]]) // scans from the end
mystrng.index(sub [, start [, end]]) // similar to find, but raises ValueError if not found instead of returning −1.
mystrng.rindex(sub [, start [, end]])
mystrng.count(sub [, start [, end]]) // counts the number of nonoverlapping occurrences
mystrng.startswith(sub [, start [, end]]) // True if string s starts with substring sub. 
mystrng.endswith(sub [, start [, end]])


iter(object [, sentinel]) // returns an iterator that can be stepped through.
enumerate(iterable, start=0) // returns an iterable enumerate object.
all(iterable) // Returns True only if all elements of the iterable are true.
any(iterable) // Returns True only if any element of the iterable is true.
next(iterator [, default])//Retrieves the next item from the iterator 
map(function, iterable [, iterable]*) // applies function to each item of iterable and returns individual results.
filter(function, iterable) // Returns elements of iterable for which function returns true.
sum(iterable [, start]) // sums start and the items of an iterable, from left to right, and returns the total.

The import Statement

import module [, module]*
import [package.]* module [, [package.]* module]*
import [package.]* module as name
[, [package.]*module as name]*
from [package.]* module import name [, name]*
from [package.]* module import *
from [package.]* module import name as someothername
from [package.]* module import (name1, name2, ...)

OOP in Python

Python Class Definitions

class XYZ:
"""A docstring description of the class"""
...def __init__(self):# initialization method
......statement 1
......statement 2
...def method1(self,a,b ):
......statement 3
......statement 4

Object instantiation

class my-class(class-to-be-inherited):
def __init__(self):
#initialization (constructor) code goes here

To use this class in a program use:foo = my-class()

Private and public variables and methods

  • Unless you specify, all variables and methods are public and virtual
  • Any name which begins with a double-underscore (__) is private
  • Any name which begins with a single underscore (_) is protected

Other in-built OOP methods:

__init__(self [, arg]*) //constructor
delattr(object, name) // deletes the attribute named name (a string) from object. 
getattr(object, name [, default]) // returns the value of attribute name from object
hasattr(object, name) // Returns true if object has an attribute called name
id(object) // returns the unique identity integer of object which is its address in memory
isinstance(object, classname) // Returns true if object is an instance of classname
issubclass(classA, classB) // returns true if classA is subclass of classB.
super([type [, object-or-type]]) // returns the superclass of object.

Try /Catch

[except [type [as value]]:

Other Built-in Functions

abs(X) : returns the absolute value of a number N.
bin(X) // Convert integer to a binary digits
bool([x]) // Converts a value to a Boolean, using the truth table formula
compile(string, filename, kind [, flags[, dont_inherit]])// generates the .pyc bytecode
dir([object]) // returns the list of names in the current local namespace.
int([number | string [, base]]) // converts a number or string to a integer. default base 10.
float([X]) // Converts a number or a string X to a floating-point number
globals() // returns a dictionary containing the global variables

PDF Download
You can also download this python cheatsheet pdf document.

Closing Remarks & Errata
Update: I have updated this page several times since the original pdf was created.The pdf is not update. For a complete list, copy and paste the cheatsheet. Will soon update the pdf.
I have taken the best care to ensure that everything in this cheatsheet is upto mark. However, I am no expert at python.
If you come across any error or if you think this cheatsheet should be changed for better, please leave me a comment below.