CSCI 1101A Introduction to Python Ch. 2 to 5 [Guttag] Mohammad T . - - PDF document

csci 1101a
SMART_READER_LITE
LIVE PREVIEW

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


slide-1
SLIDE 1

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

slide-2
SLIDE 2

9/24/14 ¡ 2 ¡

Writing a program in IDLE

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

Basic Elements of Python

slide-3
SLIDE 3

9/24/14 ¡ 3 ¡

Statement (or command)

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

Comments

u # Single line comment u ‘‘‘

Multiple lines

  • f

comments ’’’

slide-4
SLIDE 4

9/24/14 ¡ 4 ¡

Objects

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

Expressions

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

slide-5
SLIDE 5

9/24/14 ¡ 5 ¡

Expressions

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

Variables and assignment

Remember: Assignment works right to left

slide-6
SLIDE 6

9/24/14 ¡ 6 ¡

Conditional Statements

if-else

u An if block can be optionally

associated with an else block x = 10

if x%2 == 0: print x, 'is even' else: print x, 'is odd'

Note the indentation

slide-7
SLIDE 7

9/24/14 ¡ 7 ¡

Spice it up… Can we take x as an input? x = input(“Enter an integer #: ”)

if x%2 == 0: print x, 'is even' else: print x, 'is odd'

Spice it even more… Use a function

Header Body: Note the indentation

Function name Parameters

def oddEven(x):

if x%2 == 0: print x, 'is even' else: print x, 'is odd'

More on functions later

  • n ...

How to use this function?

slide-8
SLIDE 8

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’

if-elif-else

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

Quiz

u What will be the output?

x = 0 if x >= 0: print "non-negative" elif x <= 0: print "non-positive"

slide-9
SLIDE 9

9/24/14 ¡ 9 ¡

Exercise (p. 16)

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"

Iterative Statements/ Loops

slide-10
SLIDE 10

9/24/14 ¡ 10 ¡

while loop

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

Body while loop (cont…)

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

Body

slide-11
SLIDE 11

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

while loop (cont…)

This line is crucial!

Test

for loop

u General form (not actual code)

u for loop_variable in sequence:

body of for loop

slide-12
SLIDE 12

9/24/14 ¡ 12 ¡

range function

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

  • utputs a list.

More coming soon…

for loop

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

slide-13
SLIDE 13

9/24/14 ¡ 13 ¡

for loop (cont…)

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

for loop (cont…)

slide-14
SLIDE 14

9/24/14 ¡ 14 ¡

Nested Loops break statement continue statement

Problem: print a pyramid of n lines

  • f numbers

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

slide-15
SLIDE 15

9/24/14 ¡ 15 ¡

Nested loop exercise

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

break statement

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

slide-16
SLIDE 16

9/24/14 ¡ 16 ¡

continue statement

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

Non-scalar object String

slide-17
SLIDE 17

9/24/14 ¡ 17 ¡

String

u Examples

u “Hello and welcome” u “Bowdoin College”

u Assignment statement

u college = “Bowdoin College”

Operations on String

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']

slide-18
SLIDE 18

9/24/14 ¡ 18 ¡

Taking a string as input

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? ’)

What is the difference between “57” and 57?

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’

slide-19
SLIDE 19

9/24/14 ¡ 19 ¡

Non-scalar object List

List

u Ordered sequence of values u Each value is identified by an index u Example

slide-20
SLIDE 20

9/24/14 ¡ 20 ¡

More examples of list

u A list may contain heterogeneous data

myList = [“I did it all”, 4, “love”] for i in myList: print i

List vs. string: similar operations

u Concatenation

slide-21
SLIDE 21

9/24/14 ¡ 21 ¡

List vs. string: similar operations

u Length function: len() u x = “Hello”

y = [2, 30, 55] print len(x) # 5 print len(y) # 3

List vs. string: similar operations

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]

slide-22
SLIDE 22

9/24/14 ¡ 22 ¡

List: additional functions (not in string)

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’

More list functions

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)

slide-23
SLIDE 23

9/24/14 ¡ 23 ¡

List Comprehension [Advanced]

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]

for loop on strings and lists

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

slide-24
SLIDE 24

9/24/14 ¡ 24 ¡

More for loop example: Calculate average—2 different ways

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

Functions

slide-25
SLIDE 25

9/24/14 ¡ 25 ¡

Function definition

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

return statement

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

slide-26
SLIDE 26

9/24/14 ¡ 26 ¡

What is the difference between return and print?

Replacing this line with

print x

generates error Why?

Later on...

u Scoping u Local and global variables u Interaction among functions

slide-27
SLIDE 27

9/24/14 ¡ 27 ¡

Assignment Statement y = x

[Advanced]

More about assignment: y = x

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

slide-28
SLIDE 28

9/24/14 ¡ 28 ¡

More about assignment: y = x

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]

Parameter passing

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

slide-29
SLIDE 29

9/24/14 ¡ 29 ¡

Sorting

Bubble sort algorithm

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

slide-30
SLIDE 30

9/24/14 ¡ 30 ¡

Python code Selection sort algorithm

u Input: a list of numbers u Output: the same list, sorted low to high u Algorithm:

For each index i do the followings:

  • 1. Find the index j of the min number of the list

beginning from index i to the end of the list

  • 2. Swap the numbers at index i and index j
slide-31
SLIDE 31

9/24/14 ¡ 31 ¡

Python code Brain Teaser

u How many comparisons would you be making

in each function?

The big O notation

slide-32
SLIDE 32

9/24/14 ¡ 32 ¡

Speed (complexity) of an algorithm

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)

slide-33
SLIDE 33

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)

Road map

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]

slide-34
SLIDE 34

9/24/14 ¡ 34 ¡

Remember to practice the codes!