0% found this document useful (0 votes)
73 views

Python 3.6 Quick Reference Sheet

This document provides a quick reference for common Python syntax structures, built-in functions, data types, operators, and methods. It includes summaries of assignment statements, conditionals, loops, functions, classes, modules, exceptions, strings, lists, tuples, files and more.

Uploaded by

Taimoor Hassan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views

Python 3.6 Quick Reference Sheet

This document provides a quick reference for common Python syntax structures, built-in functions, data types, operators, and methods. It includes summaries of assignment statements, conditionals, loops, functions, classes, modules, exceptions, strings, lists, tuples, files and more.

Uploaded by

Taimoor Hassan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Python 3.

6 Quick Reference Sheet Common Syntax Structures Common Built--‐in Functions


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

You might also like