Python 2.7 Quick Reference Sheet ver 2.01-110105 (sjd) Interactive Help in Python Shell Common Syntax Structures Common Built-in Functions help() Invoke interactive help help(m) Display help for module m help(/) Display help for function / dir(m) Display names in module m Small Operator Precedence Table func_name(args,...) Function call x[index: index] Slicing x[index] Indexing x. attribute Attribute reference ** Exponentiation *, 1, % Multiply, divide, mod +, - Add, subtract >, <, <=, >=, !=, == Comparison in, not in Membership tests not, and, or Boolean operators NOT, AND, OR Module Import import module_name from module_name import name,... from module_name import * Common Data Types Type Description Literal Ex int 32-bit Integer 3, -4 long Integer > 32 bits 101L float Floating point number 3.0, -6.55 complex Complex number 1.2J bool Boolean True, False str Character sequence "Python" tuple Immutable sequence (2, 4, 7) list Mutable sequence [2, x, 3.1] diet Mapping {x:2, y:5} Assignment Statement var= exp Console Input/Output var= input( [prompt] ) var= raw_input( [prompt] ) print exp[,]... Selection if (boolean_exp): stmt... [elif (boolean_exp): stmt...]... [else: stmt...] Repetition while (boolean_exp): stmt... Traversal for var in traversable_object: stmt... Function Definition def function_name( parmameters): stmt... Function Call function_name( arguments) Class Definition class Class_name [ (superclass) ]: [ class variables ] def method_name( self, parameters ): stmt Object Instantiation obj_ref= Class_name( arguments) Method Invocation obj_ref.method_name( arguments) Exception Handling try: stmt... except [exception_type] [, var]: stmt... Function Returns abs(x) Absolute value of x dict() Empty dictionary, eg: d = dict() float(x) int or string x as float id(ofy) memory addr of obj int (x) float or string x as int len(s) Number of items in sequence s listO Empty list, eg: m = list() max(s) Maximum value of items in s min(s) Minimum value of items in s open(/) Open filename/for input ord(c) ASCII code of c pow(x,y) x ** y range(x) A list of xintsOtox-1 round(x,n) float x rounded to n places str(oby) str representation of obj sum(s) Sum of numeric sequence s tuple(/fems) tuple of items type(ofy) Data type of obj Common Math Module Functions Function Returns (all float) ceil(x) Smallest whole nbr >= x cos(x) Cosine of x radians degrees(x) x radians in degrees radians(x) x degrees in radians exp(x) e ** x floor(x) Largest whole nbr <= x hypot(x, y) sqrt(x * x + y * y) log(x [, base]) Log of x to base or natural log if base not given pow(x, y) x ** y sin(x) Sine of x radians sqrt(x) Positive square root of x tan(x) Tangent of x radians Pi Math constant pi to 15 sig figs e Math constant e to 15 sig figs Common String Methods S.method() Returns (str unless noted) capitalize S with first char uppercase center(w) S centered in str w chars wide count(stvfa) int nbr of non-overlapping occurrences of sub in S find(stvb) int index of first occurrence of sub in S or -1 if not found isdigit() bool True if S is all digit chars, False otherwise islower() isupper() bool True if S is all lower/upper case chars, False otherwise join(seq) All items in seq concatenated into a str, delimited by S lower() upper() Lower/upper case copy of S lstrip() rstrip() Copy of S with leading/ trailing whitespace removed, or both split([sep]) List of tokens in S, delimited by sep; if sep not given, delimiter is any whitespace Formatting Numbers as Strings Syntax: "format_spec" % numeric_exp format_spec syntax: % width.precision type • width (optional): align in number of colums specified; negative to left-align, precede with 0 to zero-fill • precision (optional): show specified digits of precision for floats; 6 is default • type (required): d (decimal int), f (float), s (string), e (float - exponential notation) • Examples for x = 123, y = 456.789 "%6d" % x -> ... 123 "%06d" % x -> 000123 "%8.2f %y->. .456.79 "8.2e" % y -> 4.57e+02 "-8s" % "Hello" -> Hello . .. Common List Methods Lmethod() Result/Returns append(ofay) Append obj to end of L count(ofay) Returns int nbr of occurrences of obj in L index(ofay) Returns index of first occurrence of obj in L; raises ValueError if obj not in L pop([index]) Returns item at specified index or item at end of L if index not given; raises IndexError if L is empty or index is out of range remove(ofay) Removes first occurrence of obj from L; raises ValueError if obj is not in L reverse() Reverses L in place sort() Sorts L in place Common Tuple Methods r.method() Returns count(ofay) Returns nbr of occurrences of obj in T index(ofay) Returns index of first occurrence of obj in T; raises ValueError if obj is not in T Common Dictionary Methods D.method() Result/Returns clear() Remove all items from D get(/c [,val]) Return D[k] if k in D, else val has_key(/c) Return True if k in D, else False items() Return list of key-value pairs in D; each list item is 2-item tuple keys() Return list of D's keys pop(/c, [val]) Remove key k, return mapped value or val if k not in D valuesQ Return list of D's values Common File Methods F.method() Result/Returns read([n]) Return str of next n chars from F, or up to EOF if n not given readline([n]) Return str up to next newline, or at most n chars if specified readlinesQ Return list of all lines in F, where each item is a line write(s) Write str s to F writelines(/.) Write all str in seq L to F close() Closes the file Other Syntax Hold window for user keystroke to close: raw_input("Press to quit.") Prevent execution on import: if_name_== "_main_": main() Displayable ASCII Characters 32 SP 48 0 64 @ 80 P 96 112 P 33 ! 49 1 65 A 81 Q 97 a 113 q 34 ii 50 2 66 B 82 R 98 b 114 r 35 # 51 3 67 C 83 S 99 c 115 s 36 $ 52 4 68 D 84 T 100 d 116 t 37 % 53 5 69 E 85 U 101 e 117 u 38 & 54 6 70 F 86 V 102 f 118 V 39 55 7 71 G 87 w 103 g 119 w 40 ( 56 8 72 H 88 X 104 h 120 X 41 ) 57 9 73 1 89 Y 105 i 121 y 42 * 58 74 J 90 z 105 j 122 z 43 + 59 I 75 K 91 [ 107 k 123 { 44 } 60 < 76 L 92 \ 108 1 124 1 45 - 61 = 77 M 93 ] 109 m 125 } 46 62 > 78 N 94 A 110 n 126 47 1 63 ? 79 O 95 111 0 127 DEL "\0' = 0, "\t' = 9, = 10