You are on page 1of 9

Download Python 2.

X Cheatsheet & Reference Guide | KnowPapa

http://knowpapa.com/pycs/

Home

KnowPapa

Download Python 2.X Cheatsheet & Reference Guide


Comments are closed

Indentation specific about indentation. Comment: Case Sensitivity

ry

Quotes: You can use single quotes between double quote and double quotes within single quotes

Assert Statement Class and Function Decorator: @decorator Escape codes \n newline \t Horizontal tab \\ Backslash (\) \v Vertical tab

\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: greater-than, <= less-than-equal, >= greater-than-equal, != not equal, is = object identity, is not = negated object identity Data Types: Boolean: String: passed = True, failed = False,

1 of 9

22/11/2013 11:45 AM

Download Python 2.X Cheatsheet & Reference Guide | KnowPapa

http://knowpapa.com/pycs/

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 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']

Input 1 2 3 4 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 1 2 (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 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: 1 2 3 4 5 if condition: #do stuff if test is true elif condition2: #do stuff if test2 is true else: #do stuff if both tests are false

2 of 9

22/11/2013 11:45 AM

Download Python 2.X Cheatsheet & Reference Guide | KnowPapa

http://knowpapa.com/pycs/

while <condition>: for x in range (start, stop, step) Python Strings Manipulation change a part of the string. The best one can do is to create a new string as a variation on the original string. 1 2 3 4 5 6 7 foo = print print print print print print "holy cow" # string creation using single or double quotes foo[5] # returns 'c' / Rem: All indexing starts at 0. foo[2: 5] # slicing returns 'ly c' foo[:5]# returns 0 to 5th carecters foo[5:] # returns 5th to end foo.split(' ') # returns ['holy', 'cow'] foo.split( hol', ' cow']

String Formatting 1 2 3 4 5 6 7 8 %s %r %c %d %f %i %o %x //String //also used for string //Character (int or str) //Decimal (base 10 integer) //Floating- point decimal //Integer //Octal //Hex

For a Complete list of string manipulation methods available in Python type: dir(str) 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: 1 2 3 4 5 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 1 2 3 4 5 6 7 8 9 10 11 mystrng = "Some String" mystrng.capitalize() mystrng.center(width, [, fill]) mystrng.count(sub [, start [, end]]) mystrng.encode([encoding [,errors]]) mystrng.endswith(suffix [, start [, end]]) mystrng.expandtabs([tabsize]) mystrng. format(fmtstr, *args, **kwargs) mystrng.isalnum() mystrng.isalpha() mystrng.isdecimal()

3 of 9

22/11/2013 11:45 AM

Download Python 2.X Cheatsheet & Reference Guide | KnowPapa

http://knowpapa.com/pycs/

12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

mystrng.isdigit() mystrng.isidentifier() mystrng.islower() mystrng.isnumeric() mystrng.isprintable() mystrng.isspace() mystrng.istitle( mystrng.isupper() mystrng.join(iterable) mystrng.ljust(width [, fill]) mystrng.lower() mystrng.lstrip([chars]) mystrng.maketrans(x[, y[, z]]) mystrng.partition(sep) mystrng.replace(old, new [, count]) mystrng.rjust(width [, fill]) mystrng.rpartition(sep) mystrng.rsplit([sep[, maxsplit]]) mystrng.rstrip([chars]) mystrng.split([sep [,maxsplit]]) mystrng.splitlines([keepends]) mystrng.startswith(prefix [, start [, end]]) mystrng.strip([chars]) mystrng.swapcase() mystrng.title() mystrng.translate(map) mystrng.upper() mystrng.zfill(width)

File Handling 1 2 3 4 5 6 open /mydir/ # open read only file. use forward slash open /mydir/ 'w') # open file with write permission myfile.read() # 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 the complete file path using forward slash (/). For accessing the current working directory, use the os module. 1 2 3 4 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 1 2 3 4 5 6 7 foo.isupper() foo.islower() foo.isalpha() foo.isdigit() foo.isalnum() foo.isspace() foo.istitle() % % % % % % % #returns true if is upper case #returns true if is lower case # returns true if a string is alphabetical # returns true if a string is numeric # returns true if is alpha-numeric # returns true if foo is whitespace # returns true if first letter is capitalised

Python List

enclosed in square brackets [] returns a new list.

4 of 9

22/11/2013 11:45 AM

Download Python 2.X Cheatsheet & Reference Guide | KnowPapa

http://knowpapa.com/pycs/

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

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 abc def ghi can be represented as: mymatrix = [[a,b,c], [d, e, f], [g, h,i]] Other list operators 1 2 3 4 5 6 7 8 9 10 11 12 13 14 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 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[mylist.index(x)] 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. 1 2 3 4 5 6 7 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).

5 of 9

22/11/2013 11:45 AM

Download Python 2.X Cheatsheet & Reference Guide | KnowPapa

http://knowpapa.com/pycs/

# 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 {}) 1 2 3 4 5 6 7 8 9 10 11 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 1 2 3 4 5 6 7 8 9 10 11 12 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 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

Python Function Definitions 1 2 3 4 5 6 def my- func(param1, param 2. .): in triple quotes.

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

Scope of a Function To use a function/class/module in the global scope, import it in the global scope. If imported inside a rt to have a global

Python Built-in Functions Built-in Functions abs() dir() hex() next() slice()

6 of 9

22/11/2013 11:45 AM

Download Python 2.X Cheatsheet & Reference Guide | KnowPapa

http://knowpapa.com/pycs/

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

hasattr()
hash() help()

Functions to modify type of an object The following functions are used to modify type of an object:

Searching 1 2 3 4 5 6 7 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 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]])

Iterable 1 2 3 4 5 6 7 8 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 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,

The import Statement 1 2 3 4 import module [, module] * import [package.] * module [, [package.] * module] * import [package.] * module as name [, [package.] * module as name]*

7 of 9

22/11/2013 11:45 AM

Download Python 2.X Cheatsheet & Reference Guide | KnowPapa

http://knowpapa.com/pycs/

5 6 7 8

from from from from

[package.] * [package.] * [package.] * [package.] *

module module module module

import import import import

name [, name] * * name as someothername (name1, name2, ...)

OOP in Python Python Class Definitions 1 2 3 4 5 6 7 8 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 1 2 3 4 class my-class( class- to- be- inherited): def __init__(self): class- to- be- inherited.__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: 1 2 3 4 5 6 7 8 __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 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 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.

Debugging Try /Catch 1 2 3 4 5 6 7 8 9 try: block except : block [ except [type [as value]]: else: block finally: block

Other Built-in Functions 1 2 3 4 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

8 of 9

22/11/2013 11:45 AM

Download Python 2.X Cheatsheet & Reference Guide | KnowPapa

http://knowpapa.com/pycs/

5 6 7 8

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 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.
Like Share Tweet

Possibly Related
Quick Sort Algorithm in Python (1) Merge Sort Algorithm in Python (1) Insertion Sort Algorithm in Python (1) Bubble Sort Algorithm in Python (1) (1) Multi-Threaded TCP/IP Port Scanner in Python (1) Tkinter ttk Treeview Simple Demo (1) Tkinter Color Chooser Dialog Simple Demo (1) (1) A Notepad like Text Editor designed in Python & Tkinter | Code + (1)
In category: Python

Previous post: Next post: Use-Case reuse: Extend vs Include generalization in UML

Copyright 2013 KnowPapa. All Rights Reserved,

9 of 9

22/11/2013 11:45 AM