9/24/14 ¡ 1 ¡
CSCI 1101A
Introduction to Python
- Ch. 2 to 5 [Guttag]
Mohammad T . Irfan 9/9/14 – 9/25/14
Questions
u When are the readings “doings” due? u When will be the in-class exams?
u First exam: Thursday, 9/18
CSCI 1101A Introduction to Python Ch. 2 to 5 [Guttag] Mohammad T . - - PDF document
9/24/14 CSCI 1101A Introduction to Python Ch. 2 to 5 [Guttag] Mohammad T . Irfan 9/9/14 9/25/14 Questions u When are the readings doings due? u When will be the in-class exams? u First exam: Thursday, 9/18 1
9/24/14 ¡ 1 ¡
u When are the readings “doings” due? u When will be the in-class exams?
u First exam: Thursday, 9/18
9/24/14 ¡ 2 ¡
u To start IDLE
u Mac: Start terminal first (go to spotlight and type
“terminal”); in terminal, type “idle” without the quotes and hit return
u Windows: in metro/start menu type “IDLE”
u To open editor: File è New Window u Type your program and save it with extension
“.py”
u To run your program: Run è Run Module
9/24/14 ¡ 3 ¡
u print ‘Welcome to Python’ u print “What’s your name?” u print 2 + 3 * 4 u x = 2 ** 3 ** 2 u print x
Assignment statement: Assign a value 23^2 to “variable” x More about it later
u # Single line comment u ‘‘‘
Multiple lines
comments ’’’
9/24/14 ¡ 4 ¡
u Scalar – 4 types
u int (example: -10000, 200, 53) u float (example: -37.59, 28.0) u bool (example: True, False) u None
u Non-scalar
u String (example: “hello”, “57”) u List (example: [2, 3, 5, 7, 11, “primes”]) u And many other ... (You will define and create
your own non-scalar objects later on) u Object types
u Arithmetic
u x + y u x – y u x * y u x/y
u Caution: when x and y are both int, then the result is
also int (Python 2.7 truncates all decimal digits after the decimal point) – it’s called “integer division”
u Better practice: Use x//y when x and y are both int
// operator specifically means integer division
u x % y: remainder of the division x/y for int x & y u x ** y: x raised to the power y u comparison: == (equal), != (not eq), >, >=, <, <=
u Precedence – usual
9/24/14 ¡ 5 ¡
u Logical operators (on bool)
u a and b u a or b u not a
u Examples
u 3 > 2 and 3 > 4 u 3 > 2 or 3 > 4 u not 3 > 4
u Variable: named storage space
pi = 3.14159 r = 10 area = pi * r**2 print area
u You don’t need to specify type of a variable –
it’s automatically determined
u Rules of naming a variable
u Must start with a letter (upper or lower case) or _,
may contain digits after the first symbol
u Use sensible names u Cannot use reserved words
Remember: Assignment works right to left
9/24/14 ¡ 6 ¡
u An if block can be optionally
Note the indentation
9/24/14 ¡ 7 ¡
Header Body: Note the indentation
Function name Parameters
More on functions later
How to use this function?
9/24/14 ¡ 8 ¡ def showMinimum(x, y, z): if x < y and x < z: print x, ‘is min’ elif y < z: print y, ‘is min’ else: print z, ‘is min’
u if block, followed by any number of elif
blocks, followed by an optional else block
u if statements can be nested u Problem: Print the minimum of three given
numbers x, y, and z
u What will be the output?
x = 0 if x >= 0: print "non-negative" elif x <= 0: print "non-positive"
9/24/14 ¡ 9 ¡
u Write a program to find the largest odd number among
three given numbers x, y, and z.
def largestOdd(x, y, z): if x%2 == 1 and y%2 == 1 and z%2 == 1: if x > y and x > z: print x elif y > z: print y else: print z elif x%2 == 1 and y%2 == 1: if x > y: print x else: print y elif y%2 == 1 and z%2 == 1: if y > z: print y else: print z elif z%2 == 1 and x%2 == 1: if z > x: print z else: print x elif x%2 == 1: print x elif y%2 == 1: print y elif z%2 == 1: print z else: print "None is odd"
9/24/14 ¡ 10 ¡
u Problem: Print numbers 1, 2, …, 10, each on
a single line def printNumbers(): i = 1 while i <= 10: print i i = i + 1 Test
u Problem: Square a positive integer by
addition only
def square(x): times = 0 ans = 0 while (times != x): ans = ans + x times = times + 1 print ans
Can you make it work for x <= 0 as well? Hint: Book
Test
9/24/14 ¡ 11 ¡ def seriesSum(n): total = 0 x = 1 while x <= n: total = total + x x = x + 1 print total
u Write a function that takes a positive integer
number n as a parameter and calculates the sum 1 + 2 + ... + n
This line is crucial!
Test
u General form (not actual code)
u for loop_variable in sequence:
body of for loop
9/24/14 ¡ 12 ¡
u sequence is commonly specified using the
built-in range function with 3 parameters:
u start (optional, default is 0) u end (must, actually ends before this value) u increment (optional, default is 1)
u Examples
u range(10, 70, 20)
# [10, 30, 50]
u range (0, 5, 1)
# [0, 1, 2, 3, 4]
u range (0, 5)
# [0, 1, 2, 3, 4]
u range (5)
# [0, 1, 2, 3, 4]
The range function
More coming soon…
u Problem: Print numbers 1, 2, …, 10, each on
a single line def printNumbers2(): for i in range(1, 11, 1): print i
Body – multiple lines allowed Loop variable Sequence
9/24/14 ¡ 13 ¡
u Problem: Square a positive integer by
addition only
def square2(x): ans = 0 for times in range(x): ans = ans + x print ans
Can you make it work for x <= 0 as well?
Alternatives: range(0, x, 1) range (0, x) range (1, x+1, 1) range (1, x+1)
u Write a function that takes a positive integer
number n as a parameter and calculates the sum 1 + 2 + ... + n
u HW Problem: Given a number n, calculate
the sum 1 + 4 + 7 + 10 + … + (3n+1) def seriesSum2(n): total = 0 for x in range(1, n+1): total = total + x print total
9/24/14 ¡ 14 ¡
u For n = 5, we want
#Prints a pyramid of numbers with n lines #n is given as a parameter def pyramid(n): for line in range(n+1): for times in range(line+1): print line, #Prints the line number followed by a space print #This inserts a new line. Same as: print "" 1 1 2 2 2 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5
9/24/14 ¡ 15 ¡
u What would be the output?
def loopDemo(): x = 3 for j in range(x): for i in range(x): print j, i 0 0 0 1 0 2 1 0 1 1 1 2 2 0 2 1 2 2
u Used for early termination of a loop u Only terminates the immediate loop that
contains the break statement, not other loops
def loopDemo(): x = 3 for j in range(x): for i in range(x): if i > 1: break #will not print any value of i > 1 print j, i 0 0 0 1 1 0 1 1 2 0 2 1 break can be used without nested loops
9/24/14 ¡ 16 ¡
u Keeps the loop going, but skips the code
after it
u Example: want to skip printing some i values
in the middle
def loopDemo(): x = 3 for j in range(x): for i in range(x): if i == 1: continue #will skip 1 print j, i 0 0 0 2 1 0 1 2 2 0 2 2 continue can be used without nested loops
9/24/14 ¡ 17 ¡
u Examples
u “Hello and welcome” u “Bowdoin College”
u Assignment statement
u college = “Bowdoin College”
u college = “Bowdoin College” u Length of a string
u len(college)
# 15 u Indexing
u college[2]
# ‘w’
u college[-1]
# ‘e’
u college[-2]
# ‘g’ u Slicing
u college[0:2]
# ‘Bo’
u college[0:len(college)]
# ‘Bowdoin College’ u Splitting
u college.split()
# ['Bowdoin', 'College']
9/24/14 ¡ 18 ¡
u x = raw_input (‘Enter your name: ’) u y = raw_input (‘How old are you? ’)
u Suppose user enters 57 as his/her age u y’s value is “57”, not 57 u if you want to convert string “57” to number 57,
u y = int(y) # Can use a different variable name on LHS
u Alternative: y = input(‘How old are you? ’)
u Main difference is representation u You can apply all arithmetic operators on 57
u 57 + 2 u 57 * 2
u Arithmetic operations are meaningless for
“57”
u “57” + 2
# ERROR
u “57” * 2
# ‘5757’
9/24/14 ¡ 19 ¡
u Ordered sequence of values u Each value is identified by an index u Example
9/24/14 ¡ 20 ¡
u A list may contain heterogeneous data
myList = [“I did it all”, 4, “love”] for i in myList: print i
u Concatenation
9/24/14 ¡ 21 ¡
u Length function: len() u x = “Hello”
y = [2, 30, 55] print len(x) # 5 print len(y) # 3
u Other similar functions:
v = [20, 30.5, 5.1, 10.2, 100]
u Indexing
u v[2]
# 5.1
u v[-1]
# 100
u v[-2]
# 10.2
u Slicing
u v[1:3]
# [30.5, 5.1]
u v[0:len(v)]
# [20, 30.5, 5.1, 10.2, 100]
u v[0: -2]
# [20, 30.5, 5.1]
u v[:3] # [20, 30.5, 5.1] u v[2:] # [5.1, 10.2, 100] u v[:] # [20, 30.5, 5.1, 10.2, 100]
9/24/14 ¡ 22 ¡
u Lists are “mutable”, strings are not!
x = [5, 10, 15] #append an object e to x: x.append(e) x.append(20) # x is now [5, 10, 15, 20] #insert object e at index i: x.insert(i,e) x.insert(1, 7) # x is now [5, 7, 10, 15, 20] #remove the first occurrence of an object x.remove(15) # x is now [5, 7, 10, 20] #remove and return the item at a given #index i: x.pop(i) y = x.pop(2) # x = [5, 7, 20], y = 10
Add Delete
Try this: x = “hello” x[0] = ‘H’
u #sort a list (low to high)
x.sort() # x will be changed (sorted order)
u #reverse a list
x.reverse() # x will be changed (reversed)
9/24/14 ¡ 23 ¡
u Concise way to apply an operation to the values
in a sequence
x = [50, 10, 5, 500] s = [ t**2 for t in x[1:3] ] # s is [100, 25] y = [t+10 for t in range(0,3)] # y is [10, 11, 12]
def showCharacters(): st = “Bowdoin College” for x in st: print x # This will print individual characters of st def showWords(): st = “Bowdoin College” for x in st.split(): # st.split() gives [‘Bowdoin’, ‘College’] print x # This will print individual words of st
9/24/14 ¡ 24 ¡
Incorrect: integer division!
Better to write: avg = float(total)/len(x)
Loop variable: Choose any name you want Better: take x as a parameter of the function
9/24/14 ¡ 25 ¡
u def functionName (parameters):
body of function
u The return value is lost unless you save it!
max (10, 20) # max returns 20, but it’s lost t = max (10, 20) # t will hold 20
u Function exits right after encountering either
u a return statement: returns the specified value u the last statement in its body: returns None if it
does not return anything
9/24/14 ¡ 26 ¡
Replacing this line with
print x
generates error Why?
u Scoping u Local and global variables u Interaction among functions
9/24/14 ¡ 27 ¡
u If x (and y) are scalar
u The value of x is copied to the storage space of y u They don’t share the same storage space
u Test it
x y 10.5 10.5
x = 10.5 y = x x = 500.01 print y # prints 10.5
x y 500.01 10.5
9/24/14 ¡ 28 ¡
u If x (and y) are non-scalar
u x and y both share the same storage space
u Test it: u If you assign a new object (scalar/non-scalar)
to x, then x and y will stop sharing space
x y [2, 3, 5]
x = [2, 3, 5] y = x x.append(10) print y
x y [2, 3, 5, 10]
x = [10, 20] print y
x y [2, 3, 5, 10] [10, 20]
def f(y): # y is changed here def g(): #define a variable y here… …. f(x) print x # Will x be changed by f?
y = x happening here
9/24/14 ¡ 29 ¡
u Input: a list of numbers u Output: the same list, sorted low to high u Algorithm:
Repeat the following until no swap is done: For each index i do the following: If the numbers at index i and i+1 are unordered, fix it by swapping
9/24/14 ¡ 30 ¡
u Input: a list of numbers u Output: the same list, sorted low to high u Algorithm:
For each index i do the followings:
beginning from index i to the end of the list
9/24/14 ¡ 31 ¡
u How many comparisons would you be making
in each function?
The big O notation
9/24/14 ¡ 32 ¡
u O(1): constant time
u Example: calculate the area of a circle
u O(n): linear time
u Example: searching for the minimum number in a
list u O(n2): quadratic time
u Example: selection sort
u Other possibilities? Yes! 20 40 60 80 100 120 2 4 6 8 10 12 # of comparisons Input Size, n
Contrasting Complexities
O(n) O(n^2)
9/24/14 ¡ 33 ¡
5000000 10000000 15000000 20000000 25000000 30000000 1000 2000 3000 4000 5000 6000 # of comparisons Input Size, n
Contrasting Complexities
O(n) O(n^2)
u So far
u All the basics of Python: Ch 2 to 5 of Guttag u Some additional topics: sorting, complexity
u Coming up…
u Images, sound, files [Guzdial]
9/24/14 ¡ 34 ¡