Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.

Similar presentations


Presentation on theme: "Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University."— Presentation transcript:

1 Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University

2 Values, data types, variables Use type() to learn type of a value Variable: name that refers to a value The assignment statement creates new variables and gives them values Motto in assignment statements: evaluate right hand side, and then assign to the value of left hand side Example values Data types 12int 12.1float 1 + 3jcomplex “hello”str [1, 2, 34.5, ‘a’]list (1,4,’a’)tuple >>> a = 3 >>> a 3 >>> my_str= ‘hello’ >>> my_str ‘hello’ >>> _list1 = [1,2,3] >>> _list1 [1,2,3] >>> a,b,c = 1,2,3 # simultaneous assignment is allowed Check its use in swapping variable values!

3 Valid identifier names Module names, function names, variable names are called identifiers. Valid identifier names should comply to the following rules: – starts either with a letter or an underscore( ‘_’) – it may contain letters, digits and underscore in them. They are case sensitive. Here are examples of valid identifier names: – a – abc – my_sum – _sum – ___ – sumOf2_digits

4 Arithmetic operators Addition: + Multiplication: * Subtraction: - (Floating point) Division: / (Integer) Division: // Exponentiation: ** Mod: % What values they can operate on? Numerical values, strings? What is the resulting value and data type given the operand types? Which operation takes place first? (Operator precedence) When equal precedence, do we start evaluating from left or right? (Order of operation)

5 Type conversions, rounding int() float() implicit type conversion math.floor() round()

6 Expressions, statements An expression is a combination of values, variables, and operators. Syntactically correct expressions are evaluated by the interpreter to a single value. A statement is an instruction that the Python interpreter can execute. It is a complete command. ExpressionsValue (it evaluates to)Data type of the value 1+2/22int “a”*4 + ’bb’‘aaaabb’str [1, 2, 3] list 1, 4.5, 3/2(1, 4.5, 1.5)tuple

7 print() print() is a built-in function that displays values. >>> help(print) Help on built-in function print in module builtins: print(...) print(value,..., sep=' ', end='\n', file=sys.stdout) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline.

8 input() input() is a built-in function that prompts user for input and returns the entered string. >>> help(input) Help on built-in function input in module builtins: input(...) input([prompt]) -> string Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading.

9 eval() eval() takes an argument of string value, evaluates it and returns the resultant numeric value. >>> eval(“123”) 123 >>> eval(“1 + 2*3”) 7 >>> eval(“’1’*2”) ‘11’ Use eval() with input() to evaluate user input >>> input(“Please enter a number: ”) ‘123’ >>> eval(input(“Please enter a number: ”)) 123

10 Functions A function is a named sequence of statements that performs a desired operation. This operation is specified in a function definition. In Python, the syntax for a function definition is: def ( ): … The statements inside the function are not executed until the function is called.

11 Functions II Syntax for a function call is: ( ) Function call itself is evaluated to a value if it returns something, otherwise it evaluates to None. >>> def f(): return 3 >>>f() + 2 5 >>> def f(x, y): return x+y >>>f(3, 4) + 2 9 >>> def f(x, y): print (x+y) >>>f(3, 4) + 2 7 ERROR >>> def f(x, y): return x, y >>>a = f(3,4) >>>a (3,4) >>>a[0] 3

12 Local vs. Global scope

13 lists, tuples Create a list by enclosing items in square brackets. Create a tuple by enclosing items in parenthesis. Items are separated by commas. Lists are mutable, tuples are not >>> a = [1, 2**3, 3+4] >>> a [1,8,7] >>> a[0] 1 >>> a[2] 7 >>> len(a) 3 >>> a[2] = 3 >>> a [1,8,3] >>> b = 1, 2**3, 3+4 >>> b (1,8,7) >>> b[0] 1 >>> b[2] 7 >>> len(b) 3 >>> b[2] = 3 ERROR

14 range() iterator You can think of range() as a function that generates a list of integers. range([start,] stop [, step]) default value of start = 0, default value of step = 1 Use list() to see the list range generates. >>> list( range(1,4)) #Example with start & stop values. [1, 2, 3] >>> list( range(1,10,2)) #Example with start, stop, and step. [1, 3, 5, 7, 9] >>> list(range(5, -6)) #List is empty in this is case. [] >>> list(range(5, -6, -1)) #Can have a negative step. [5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5]

15 for-loops for-loops allow us to repeat code a specified number of times. Syntax: for in : … >>> for i in [1, 5, 7]: print(i) 1 5 7 >>> >>> for i in range(3): print(i) 0 1 2 >>> >>> for i in range(3): print(i, end =‘ ‘) print(‘a’,end=‘ ‘) print() print(“hello”) 0 a 1 a 2 a hello >>>

16 for-loops II def f(x, y): k = 1 t = 2 for i in range(1,4): k = k + x t = t + y x = x + i return x, y, k, t result = f(3, 4) xykti beginning3412- After first iteration 44461 After second iteration 648102 After third iteration 9414 3 After this code is executed, result has the following value: (9, 4, 14, 14) Tracing a for-loop!

17 Some algorithmic patterns Recursive application of a function on a starting value to generate a sequence # x0 : starting value of the sequence to generate # num: number of terms to generate # prints the sequence generated by the recursive application # of function f() # f() is assumed to return the next value in the #sequence, # given the previous value def seq(x0, num): k = x0 for i in range (num): print (k, end = ' ') k = f(k)

18 Some algorithmic patterns II To build up, or accumulate, a final value piece by piece, use an accumulator variable. my_sum = 0 # initialize the accumulator variable for i in range(1,5): my_sum = my_sum + i print(my_sum) # my_sum’s value is the sum of ints in range[1,4] fact = 1 # initialize the accumulator variable for i in range(2, n+1): fact = fact * i print(fact) # fact’s value is n! (read as n factorial)


Download ppt "Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University."

Similar presentations


Ads by Google