programming for engineers in python -...
TRANSCRIPT
Recitation 2
Programming for Engineers in Python
Plan
Range
For loop
While loop
Lists
Modules
Operations Arithmetic Operations:
+ plus
- minus
* multiply
/ divide (int / float)
% modulo (remainder)
** power
Comparison Operators (Return True or False):
== equal
!= not equal
> greater than
< less than
>= greater than or equal to
<= less than or equal to
Range Creates an ordered collection of all integers in a given range.
range(a, b) contains all integers k satisfying a ≤ k < b.
range(b) is a shorthand for range(0, b).
>>> range(0,10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(-2,2)
[-2, -1, 0, 1]
>>> range(4,2)
[]
>>> type(range(3))
<type 'list„> # coming soon
Range – Cont.
range(a,b,d), returns the list: a, a+d, a+2d,…, a+id until
b is reached.
>>> range(0,10,2)
[0, 2, 4, 6, 8]
>>> range(10,0,-2)
[10, 8, 6, 4, 2]
>>> range(0, 10, -1)
[]
>>> range(0,10,0)
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
range(0,10,0)
ValueError: range() step argument must not be zero
For Loop for elem in list (TBD):
statement1
statement2
…
Compute 1 + 2 + … + 100:
partialSum = 0
for i in range(1,101):
partialSum = partialSum + i
print partialSum
5050
determines the scope of the iteration.
“Cheat”:
sum(range(1,101))
For Loop – Cont.
Iterate over strings:
name = “Assaf”
for letter in name.upper():
print 'Give me', letter
print 'What did we get?', name
Give me A
Give me S
Give me S
Give me A
Give me F
What did we get? Assaf
While Loop # Find the smallest divisor
n = 9
div=2
while n % div != 0:
div = div+1
print "Smallest divisor of“,n,"is",div
is the while loop above infinite?
While Loop – Cont. # Find prime
if n < 2:
print “Out of range"
If div != n:
print div," is a divisor of “,n
else:
print n," is prime"
While Loop
while [expression]:
statement1
statement2
…
Infinite loop:
i = 1
while i < 4:
print i
expr
statement(s)
true
false
# Find smallest divisor using For:
for div in range(2, n+1):
if n % div == 0:
break
print div
For / While Equivalence
Break - Aborting Iteration
break terminates the nearest enclosing loop, skipping the code that follows the break inside the loop.
Useful for getting out of loops when some predefined condition occurs.
>>> for i in range(1,10):
print(i)
if i % 3 == 0:
break
1
2
3
Lists
A list is an ordered sequence of elements.
The simplest way to create a list in Python:
Enclose its elements in square brackets.
>>> my_list = [2,3,5,7,11]
>>> my_list
[2,3,5,7,11]
Lists are Indexable Remember this?
The same indexing + slicing works for lists!
o
l
l e
H
4
3
2
1
0
-1 -2 -3 -4 -5
Slicing
>>> my_list = [1,2,3,4,5,6,7,8,9,10]
>>> my_list[1:5] # slicing
[2,3,4,5]
>>> my_list[0:-1:2] # slicing an arithmetic progression
[1,3,5,7,9]
>>> my_list[::2] # shorthand for previous slicing
[1,3,5,7,9]
Slicing – Cont. >>> my_list[::-1] # going backwards
[10,9,8,7,6,5,4,3,2,1]
>>> my_list[3:8:-2]
[ ] # output is an empty list. This is NOT an error
>>> my_list
[1,2,3,4,5,6,7,8,9,10] # slicing does NOT change
original list
Lists are Indexable – Cont. 0 1 2 3 4
>>> my_list = [2, 3, 5, 7, 11]
>>> my_list[0]
2
>>> my_list[4]
11
>>> my_list[5]
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
my list[5]
IndexError: list index out of range
>>> my_list[2:4]
[5, 7]
Lists – Cont. Iterate:
>>> sum_list = 0
>>> for k in my_list:
sum_list += k # shortcut for sum_list = sum_list + k
>>> sum_list
28
Create lists:
range(…) creates a list
>>> new_list = [i**2 for i in my_list]
>>> new_list
[4, 9, 25, 49, 121]
Length of Lists
len returns the length (number of elements) of a list.
>>> len(my_list)
5
>>> len([])
0
Quite often, the length is a useful quantity to have.
Lists, Strings, and Beyond
Lists can contain strings:
days = [“Sunday”, “Monday", "Tuesday”, “Wednesday”,
“Thursday”, “Friday”, “Saturday”]
>>> s = “”.join(days)
'SundayMondayTuesdayWednesdayThursdayFridaySaturday„
>>> s.lower()
'sundaymondaytuesdaywednesdaythursdayfridaysaturday„
>>> s.find('y')
5
>>> first = s[:s.find('y')+1] # what does first contain?
>>> first = first[::-1] # and now?
Nested Lists >>> mat = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
>>> mat[1]
[4, 5, 6]
>>> for row in mat: # swap rows and columns
for col in row:
print col, # , - continue the same line
1 2 3
4 5 6
7 8 9
What is len(mat) ?
Lists – Dynamic Mixing types: assume you want to maintain a list of the
students in this course either by name or by id:
students = ]„Itay‟,9255587, „Alon‟, „Zohar‟,744554887]
print students[2]
>>> „Alon‟
Michal decided to join the course, so we update the list:
# append - add an element to the end of the list
>>> students.append('Michal')
>>> students
['Itay', 9255587, 'Alon', 'Zohar', 744554887, 'Michal']
Lists – Dynamic But Alon wants lo leave the course:
>>> students.remove('Alon')
>>> students
['Itay', 9255587, 'Zohar', 744554887, 'Michal']
remove removes only the first occurrence of a value.
Functions def function_name(argument1, argument2,...):
statement1
statement2
…
return result1, result2, … # optional
Calling func:
[var1, var2,…[ = function_name(val1, val2,...)
A function is:
A named code scope
Can receive input parameters
Can return output parameters
Palindromes
Palindromes are read identically from right and left.
Examples:
ילד בדלי
A Man, A Plan, A Canal, Panama
Never odd or even
…
Pseudo-code: Translate from definition to code
- For every index in the string:
- Check if word[i] == word[len – i – 1] # why -1?
- False: this is not a palindrome
- If all indices “survived” – this is a palindrome
ו נ ש ר פ
נ ת ב ע ר
ש ב ד ב ש
ר ע ב ת נ
ף ר ש נ ו
Palindromes – Code
def is_palindrome(word):
middle = len(word)/2
for i in range(middle):
if word[i] != word[-i-1]: # no palindrome
return False
return True # matches all the way
Is there a shorter code for identifying
palindromes?
Functions – Scope Consider the following function, operating on two
arguments:
def linear_combination(x,y):
y=2*y
return (x+y)
The formal parameters x and y are local, and their “life
time" is just the execution of the function. They
disappear when the function is returned.
linear_combination
x, y
3, 4 11
Functions – Scope >>> a=3
>>> b=4
>>> linear combination(a,b)
11 # this is the correct value
>>> a
3
>>> b
4 # b has NOT changed
The change in y is local - inside the body of the
function.
Functions – Scope >>> x=3
>>> y=4
>>> linear_combination(x,y)
11 # this is the correct value
>>> x
3
>>> y
4
The y in the calling environment and the y in the
function are not the same variable!
Exercise – Unit Testing
My Code
Test
(1) Run my code
with some input (2) Check the output
Exercise – Unit Testing Use the given implementation:
- Download hw1.py
- Fill in the necessary code instead of the remarks
# +++your code here+++
- Instead of printing the code to the shell, return it to the testing function.
- “Run Module”
Example‟s output:
OK got: 'Number of donuts: 4' expected: 'Number of donuts: 4'
OK got: 'Number of donuts: 9' expected: 'Number of donuts: 9'
OK got: 'Number of donuts: many' expected: 'Number of donuts: many'
OK got: 'Number of donuts: many' expected: 'Number of donuts: many'
Module
Python Code Hierarchy
Statement
function
Package
Modules
All modules and their contents (functions, constants) can be found at
http://docs.python.org/modindex.html
>>> import math # mathematical functions
>>> dir(math) ['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan',
'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp',
'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot',
'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow',
'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
>>> math.pi # a constant
3.141592653589793
>>> math.sqrt(16) # a function
4.0 >>> math.log(8, 2)
3.0
Modules – Cont. >>> import os #operating system interfaces
>>> os.rename(„my_file.txt‟, „your_file.txt‟)
>>> os.mkdir(„new_dir‟)
>>> for root, dirs, files in os.walk('lib/email'):
print root, "consumes",
print sum(getsize(join(root, name)) for name in files),
print "bytes in", len(files), "non-directory files"
>>> os.times()[0] # user time
10.1244649