Python 3 Quick Reference Guide Comment Symbol is a hash ( # ) # this is a comment (single line) Multiline string character ( ‘ ’ ’ ) (3 single quotes) ‘ ‘ ‘ this is a multiline string. It can span multiple lines ‘ ‘ ‘ Line continuation character - backslash ( \ ) Python’s line continuation character is a Backslash. This is required if a statement is continued on the next line(s). Arithmetic Operators + Addition Subtraction * Multiplication % Modulus (integer remainder) / Division (floating-point) // Integer quotient (int or float operands) ** Exponentiation + string concatenation operator Remember to distinguish between integers and floating-point numbers. Integers are stored differently than floatingpoint numbers in memory and they are different object types: integer floating-point <class ‘int’> <class ‘float’> integers: 2, 3, -5, 0, 8 floating-point: 2.0, .5, -7., 3.1415 Relational Operators < Less than <= Less than or equal to > Greater than >= Greater than or equal to != Not equal to == Equal to (compares objects) Logical Operators not / and / or Assignment Operators = simple assignments += compound assignment (also -=, *=, /=, %=) x += 10 --> x = x + 10 -= subtraction/assignment *= multiplication/assignment /= division/assignment %= modulus/assignment += string concatenation “my_opinion” += " take it or leave it… " Special Operators is compares references # a is b [ vs a == b ] in tests membership # x in list_c Last Update: Friday, March 11, 2016 Types of Objects Everything you create in Python is an object – strings, tuples, lists, dictionaries, sets, integers, floating-point numbers, etc. Python Range range( [start=0, ] stop [ ,step=1 ] ) the start and the step are optional Examples: Variables in Python do not store values. Variables always store a reference to an object! A variable name is an alias. Python Collections a = (1,2,3) # a is a tuple b = [4,5,6] # b is a list c = {7,8,9} # c is a set d = { ‘a’:1, ‘b’:2} # d is a dict x = 3 x stores a reference to a <class ‘int’> object with the value 3 y = 5.4 y stores a reference to a <class ‘float’> object with the value 5.4 s = ’hi’ s stores a reference to a <class ‘str’> object with the value ‘hi’ Numeric Types integer <class ‘int’> floating-point <class ‘float’> complex <class ‘complex’> e.g. (3+5j) String Type string <class ‘str’> Note: strings may be enclosed in single, double or triple quotes. String slicing [start] : [stop] [: step] s=’Hello World’ s[:] --> ‘Hello World’ s[:5] --> ‘Hello’ s[6:] --> ‘World’ Sequence Types tuple list set range string (3,4,5) <class ‘tuple’> [3,4,5] <class ‘list’> {5,3,4} <class ‘set’> range(1,6) <class ‘range’> ‘abcdefghijk’ <class ‘str’> A dict is a map type key maps to value dict { ‘A’:65, ‘B’:66 } <class ‘dict’> ‘A’ is a key, 65 is a value Class Conversions ( string <--> int <--> float ) p = int( input(‘Enter an integer: ‘) ) q = float( input('Enter your hourly rate') ) r = int( ‘123’ ) s = float( "88.26" ) t = str( 2013 ) Popular Python Imports import math (precede functions with math.) ceiling(x), floor(x), sqrt(x) math.e, math.pi import random random.randint( first, last ) random.random( ) --> [0, 1) Import sys sys.exit(), sys.stdin, sys.stdout r = range(5) # r is <class ‘range’> () [] {} {k:v} Collection Conversions: set <--> tuple <--> list e = tuple(c) # set --> tuple f = list(a) # tuple --> list g = set(b) # list --> set h = tuple(d) # dict --> tuple I = set(r) # range --> set Iteration over a Collection for j in a: # over a tuple for j in b: # over a list for j in c: # over a set for j in d: # over a dict for j in r # over a range Python Mutability A list is mutable All other ojects in Python are immutable Input statement input( prompt ) --> returns a string n_str = input(“Enter an integer”) n = int(n_str) # convert str --> int Print Statement print( items [ ,sep= ] [ ,end= ] ) default sep = ’ ‘, default end = ‘\n’ m = 11, d = 6, y = 2015 print(m, d, y) --> 11 6 2015 (‘\n’) print(m +’/’ + d + ‘/’ + y) prints --> 11/6/2015 (‘\n’) Formatted Output print( string [ .format( )] ) print( “{} are a {}”.format(‘You’, 10) ) prints --> You are a 10 (‘\n’) Python Attributes type( ) --> class of an object input() type(‘s’) --> <class ‘str’> type(5) --> <class ‘int’> id( ) print() --> address of an object Python 3 Quick Reference Guide Selection and Loop Structures Selection: Unary or single selection Binary or dual selection Case structure possible when branching on a variable Simple selection One condition Compound selection Multiple conditions joined with and / or operators Looping: Python uses Pre-test loops The test precedes the body of the loop while for Loop Control: Expressions that are used to control a while loop: initialize test update (done automatically in a for loop) Counter-controlled loops, aka definite loops, work with a loop control variable (lcv). Can be a for loop or a while loop Sentinel-controlled loops, aka indefinite loops, work with a sentinel value. A while loop is used for indefinite loop Last Update: Friday, March 11, 2016 If Statement (selection structure) Simple if if test: statement(s) -------------------------------------------------------------------------------if / else if test: statement(s) else: statement the continue statement skips the rest of the statements in the body of the loop and proceeds to the test expression. The loop is not exited unless the test expression evaluates to False. Python suite: Unlike C++ and Java, curly braces are not used to create a block. Python uses indentation to create a suite. Examples if x < y: print( ‘x < y’ ) for x in range(1,6): print( x**2, end=’ ‘ ) Popular Functions round(num, digits) sum(iter) --> sum( [1,2] ) len(obect) ord(‘A’), chr(65) help( ) Example if x < y: x += 1 else: x -= 1 -------------------------------------------------------------------------------if / elif / else (nested if) if test: statement(s) elif test: statement(s) else: statement(s) Range Expressions Example if x < y: x += 1 elif x < z: x -= 1 else: y += 1 range( [start=0,] stop [,step=1] ) generates values in the range start to stop-1 [start, stop) range(1, 11) # generates numbers 1 - 10 # start=1, stop = 11, step=1 range(2, 21 ,2) # generates even numbers 2 – 20 # start=2, stop=21, step=2 Note: The break and continue statements can be used to modify the behavior of a loop the break statement exits a loop and starts executing the next statement Example if x < y: x += 1 For Loop statement (repetition structure) Form: for iterable-expr: suite Example: sum = 0 for n in range(1,11): sum += n Note: The for loop iterates over a collection for x in range(5) for x in ‘abcde’: for x in [1,2,3,4,5]: evens = (2,4,6,8,10) for x in evens: While Loop statement (repetition structure) Python Empty Statement pass Use when a statement is required but none is needed or as a placeholder. Python Null reference None x = None # x is <class 'NoneType'> [ pre-test loop ] [ pre-test loop ] Form: Example: initialize n,sum = 1,0 while boolean-expr: suite (update-expr) while n <= 10: sum += n n += 1 Python loops: may also include an else suite ( for/while … else ) may use keywords break and continue to alter the flow of execution in the loop no direct support for a post-test loop