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

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

Embed Size (px)

Citation preview

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

Exam 1 Review

Instructor – Gokcen Cilingir

Cpt S 111, Sections 6-7 (Sept 19, 2011)

Washington State University

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

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

12 int

12.1 float

1 + 3j complex

“hello” str

[1, 2, 34.5, ‘a’] list

(1,4,’a’) tuple

>>> a = 3>>> a3>>> 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!

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

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

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

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)

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

Type conversions, rounding

• int() • float()• implicit type conversion• math.floor()• round()

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

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.

Expressions Value (it evaluates to) Data type of the value

1+2/2 2 int

“a”*4 + ’bb’ ‘aaaabb’ str

[1, 2, 3] [1, 2, 3] list

1, 4.5, 3/2 (1, 4.5, 1.5) tuple

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

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.

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

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.

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

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

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

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 <function_name>(<parameter_list>): <indented_code><indented_code>…

• The statements inside the function are not executed until the function is called.

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

Functions II• Syntax for a function call is:

<function_name>(<value_list>)

• Function call itself is evaluated to a value if it returns something, otherwise it evaluates to None.

>>> def f(): return 3

>>>f() + 25

>>> def f(x, y): return x+y

>>>f(3, 4) + 29

>>> def f(x, y): print (x+y)

>>>f(3, 4) + 27ERROR

>>> def f(x, y): return x, y

>>>a = f(3,4)>>>a(3,4)>>>a[0]3

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

Local vs. Global scope

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

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] = 3ERROR

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

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]

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

for-loops

• for-loops allow us to repeat code a specified number of times. Syntax:

for <loop_variable> in <sequence>: <indented_code> <indented_code> …

>>> for i in [1, 5, 7]: print(i)

157>>>

>>> for i in range(3): print(i)

012>>>

>>> for i in range(3): print(i, end =‘ ‘) print(‘a’,end=‘ ‘) print() print(“hello”)

0 a 1 a 2 ahello>>>

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

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)

x y k t i

beginning 3 4 1 2 -

Afterfirst iteration

4 4 4 6 1

Afterseconditeration

6 4 8 10 2

Afterthirditeration

9 4 14 14 3

After this code is executed, result has the following value: (9, 4, 14, 14)

Tracing a for-loop!

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

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 valuedef seq(x0, num): k = x0 for i in range (num): print (k, end = ' ')

k = f(k)

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

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 variablefor i in range(1,5): my_sum = my_sum + iprint(my_sum) # my_sum’s value is the sum of ints in range[1,4]

fact = 1 # initialize the accumulator variablefor i in range(2, n+1): fact = fact * i print(fact) # fact’s value is n! (read as n factorial)