Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
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 onto another 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: Sunday, April 30, 2017 Types of Objects Everything you create in Python is an object – strings, tuples, lists, dictionaries, sets, integers, floating-point numbers, etc. Examples: Variables in Python do not store values. Variables always store a reference to an object! A variable name is an alias. 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) Python Range range( [start=0, ] stop [ ,step=1 ] ) the start and the step are optional r = range(2,11,2) # r is <class ‘range’> t = list(r) t--> [2, 4, 6, 8, 10 ] 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 () [] {} {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 Note: strings may be enclosed in single, double or triple quotes. Python Array Python does not have an array type. However, you can use a list. values = [ 0 for x in range(5) ] values --> [0, 0, 0, 0, 0] Valid subscripts are 0 – 4 inclusive String slicing [start] : [stop] [: step] s=’Hello World’ s[:] --> ‘Hello World’ s[:5] --> ‘Hello’ s[6:] --> ‘World’ Python Mutability Most objects are immutable String Type string <class ‘str’> 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 Mutable objects include: list, set, dict Immutable objects include: numeric types, string, tuple 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 type(‘s’) --> <class ‘str’> type(5) --> <class ‘int’> id( ) --> address of an object Python 3 Quick Reference Guide Last Update: Sunday, April 30, 2017 If Statement (selection structure) 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 Simple if if test: statement(s) Example if x < y: x += 1 -------------------------------------------------------------------------------if / else if test: statement(s) else: statement Example if x < y: x += 1 else: x -= 1 -------------------------------------------------------------------------------- Loop Control: Expressions that are used to control a while loop: initialize test update (done automatically in a for loop) if / elif / else (nested if) if test: statement(s) elif test: statement(s) else: statement(s) Example if x < y: x += 1 elif x < z: x -= 1 else: y += 1 Counter-controlled loops, aka definite loops, work with a loop control variable (lcv). Can be a for loop or a while loop Range Expressions Sentinel-controlled loops, aka indefinite loops, work with a sentinel value. A while loop is used for indefinite loop 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 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. for x in range(1,6): print( x**2, end=’ ‘ ) generates values in the range start to stop-1 [start, stop) For Loop statement (repetition structure) Form: for iterable-expr: suite Empty Statement: pass Use when a statement is required but none is needed or as a placeholder. isinstance function: Null reference: None x=3 isinstance (x, int) --> True isinstance (x, float) --> False isinstance (x, str) --> False x = None # x is <class 'NoneType'> x == None --> True x is None --> True [ pre-test loop ] 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] # list for x in (3,5,7,9,12) # tuple While Loop statement (repetition structure) Examples if x < y: print( ‘x < y’ ) range( [start=0,] stop [,step=1] ) [ 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