CS 105 Lecture 6: Loops Craig Zilles (Computer Science) - - PowerPoint PPT Presentation

cs 105
SMART_READER_LITE
LIVE PREVIEW

CS 105 Lecture 6: Loops Craig Zilles (Computer Science) - - PowerPoint PPT Presentation

CS 105 Lecture 6: Loops Craig Zilles (Computer Science) https://go.illinois.edu/cs105sp20 March 2, 2020 To Today 1. Warmup: Functions 2. Conditionals Short circuiting, nesting, and ternary operator if vs. if/else vs. if/elif/else


slide-1
SLIDE 1

Lecture 6: Loops

Craig Zilles (Computer Science) March 2, 2020 https://go.illinois.edu/cs105sp20

CS 105

slide-2
SLIDE 2

To Today

  • 1. Warmup: Functions
  • 2. Conditionals
  • Short circuiting, nesting, and ternary operator
  • if vs. if/else vs. if/elif/else
  • 3. Looping: conditions, body, iteration

4. for Loops (definite loops) 5. range 6. while Loops (indefinite loops)

  • 7. Next week's reading

2

slide-3
SLIDE 3

Wh What bugs are in the following code?

def add_one(x): return x + 1 x = 2 x = x + add_one(x) A) No bugs. The code is fine. B) The function body is not indented. C) We use x as both a parameter and a variable, but we are not allowed to do that D) Both B and C

3

slide-4
SLIDE 4

Sh Shor

  • rt

t Ci Circu cuiti ting

  • i am confused about the concept of short circuit
  • Python is lazy (which is a good thing if you understand it)
  • It won't evaluate Boolean expressions it doesn't need to

True or anything() is True False and anything() is False

  • Python won't evaluate the anything() part
  • Can use this to avoid running code that would get errors

(len(my_str) > 10) and (my_str[10] == 'a')

4

slide-5
SLIDE 5

Wh What does this program output?

  • A) it raises an error
  • B)
  • C)
  • D)
  • E) it prints nothing, but raises no errors

5

hello there hello there

print('hello') and print('there')

slide-6
SLIDE 6

Desi Design gn of f conditionals

  • Conditionals are for executing blocks 0 or 1 times
  • Why sometimes do we make multiple if else statements

but other times we make one big if, elif and else statement?

  • I don't understand how each of the components of the

chapter can be used in real world cases. A thing I like to do to help me better grasp the concepts, is imagine them happening in this world. So giving me more mundane scenarios of where we would be using these things would help a lot.

6

slide-7
SLIDE 7

Sh Shape of

  • f "d

"deci cision

  • n tr

tree": ": if w/o

  • else

Asked my TA to send email to all students in the class that didn't take Exam 0.

  • Step 1: make a set of all students that took Exam 0
  • Step 2: check each student in class if in the set

if student in exam0_takers: send_email(student)

7

slide-8
SLIDE 8

Sh Shape of

  • f "d

"deci cision

  • n tr

tree": ": if w/else

Company sends recruiting invitations to students with Python in their resume, sends 'nack' email to others if 'python' in resume.lower(): send_invitation(student) else: send_polite_decline(student)

8

slide-9
SLIDE 9

Ch Choos

  • osing betw

tween many alternati tives

Final exam location based on first letter of netid: [a-j] Loomis 100 [k-o] DCL 1320 [p-z] English 214

first_char = netid.lower()[0] if first_char <= 'j': location = 'Loomis 100' elif first_char <= o: location = 'DCL 1320' else: location = 'English 214'

9

slide-10
SLIDE 10

Mul Multi-wa way branches in general?

If you were choosing between 6 possibilities, what is the fewest elif statements you coud have: A) 1 B) 2 C) 3 D) 4 E) 5

10

slide-11
SLIDE 11

Nes Nesting

When to use elif and when to use else? I think there should be

  • nly 1 else in the whole program but I saw:

if sales_type == 2: if sales_bonus < 5: sales_bonus = 10 else: sales_bonus = sales_bonus + 2 else: sales_bonus = sales_bonus + 1 Can I change the first 'else' into elif?

11

slide-12
SLIDE 12

Nes Nesting

  • CS likes composition; indent + indent = nesting

12

Code Block A Code Block B (Execution determined by condition1) if condition1: Code Block E (Same indentation as A) if condition2: Code Block C (Execution determined by condition2)

slide-13
SLIDE 13

Wh Which is is no not a a va valid path through th this co code?

A) A, E B) A, B, E C) A, B, D, E D) A, B, C, D, E

13

Code Block A Code Block B (Execution determined by condition1) if condition1: Code Block E (Same indentation as A) if condition2: Code Block C (Execution determined by condition2) Code Block D (Same indentation as B)

slide-14
SLIDE 14

Te Ternary Operator

  • A common conditional pattern is of the form:

if condition: var = value1 else: var = value2

  • Many programming languages provide a short-hand:

var = value1 if condition else value2

14

slide-15
SLIDE 15

Wh What does f(7) re return?

def f(x): y = 9 if x <= 6 else -9 if x > y: return y return x

15

A) -9 B) 7 C) 9 D) -9 then 7 E) 9 then 7

slide-16
SLIDE 16

An Annou

  • unce

cements ts

  • Lab this week: Practice on conditionals and loops
  • "Number Guessing and Efficient Searching"
  • Solid Exam 1 performance: mean 83%, median 85%
  • Will process the reported issues in the coming week
  • Do you have a homework buddy?
  • If not, consider doing your HW at office hours!

16

slide-17
SLIDE 17

Loop Loops

  • What I found most confusing was how to identify a loop

and when do use one

  • The loops in general confuse me. I never know how

python knows how to execute which line of code in which order.

  • I do not understand the nested loops and still do not

understand the difference between the for and while loops.

  • I am having a hard time understanding what a loop

variable is and its purpose.

17

slide-18
SLIDE 18

Loop Loop con

  • nce

cepts ts

  • Loops are for repeating code 0 or more times (iterations)

loop condition loop body (one or more statements) post-loop stuff

  • 1. Evaluate condition
  • 2. If True, (execute body and go back to step 1)
  • 3. Do stuff after the loop

18

slide-19
SLIDE 19

Fo For loops (definite loops)

  • I am still confused on when to use a while loop vs. a for

loop.

  • Primary use of for loops:
  • Do some action for each element of a collection

for student in ['Cesar', 'Jessica', 'Sydney']: print('{0} is awesome!'.format(student))

19

slide-20
SLIDE 20

Ho How ma many y line nes will be be pr printed? d?

course_times = {'CS 105':'F9-11', 'CS 125':'MWF11-12'} for course in course_times: print(course, 'meets', course_times[course])

A) there is an error B) 1 C) 2 D) 3 E) 4

20

slide-21
SLIDE 21

Ho How ma many y line nes will be be pr printed? d?

things = [22, [33, 44], 55, [66]] for thing in things: print(str(thing))

A) there is an error B) 2 C) 3 D) 4 E) 5

21

slide-22
SLIDE 22

Unpa Unpacki king ng

  • the concept of unpacking!!
  • Extracts a collection into many variables, e.g.,
  • Number of vars on left must equal len(collection)

first, last, age = ['Craig', 'Zilles', 27]

  • Can be used to swap values: cute trick…

x = "started as x" y = "started as y" x, y = y, x

22

slide-23
SLIDE 23

Enume Enumerate

  • When do we use enumerate? Can you go over what this

does?

  • Use it when to get index when iterating thru collection

cities_by_pop = ['New York', 'Los Angeles', 'Chicago'] message = '{0} is number {1} by population' for index, name in enumerate(cities_by_pop): print(message.format(name, index + 1))

23

slide-24
SLIDE 24

Wh What is the contents of ne new_l _list?

  • rig_list = [3, 7, 22, 90]

new_list = [] for index, value in enumerate(orig_list): if (index % 2) == 0: new_list.append(value)

A) [3, 7] B) [3, 22] C) [3, 7, 22, 90] D) [7, 90] E) [22, 90]

24

slide-25
SLIDE 25

range st statements

  • Useful for generating (finite) sequences of numbers:
  • E.g., the numbers from 0 to 9

range(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] range(3, 8) # [3, 4, 5, 6, 7] range(-3, 11, 3) # [-3, 0, 3, 6, 9]

25

slide-26
SLIDE 26

Us Using ng rang nge to repe peat fixed d # # of time mes

for i in range(5): # note that i not used print('CS 105 is lit!')

26

How many lines of output will this print? A) 0 –or– there is an error B) 1 C) 4 D) 5 E) 6

slide-27
SLIDE 27

Us Using ng rang nge to get every y othe her cha har

  • rig_str = 'The quick brown fox jumped ...'

new_str = '' for index in range(0, len(orig_str), 2): new_str += orig_str[index] print(new_str) Teqikbonfxjme . is printed

27

slide-28
SLIDE 28

Loop Loop nestin ting

  • I think nested loops were the most confusing part of the
  • text. I find them incredibly difficult to read and

understand what is happening in them. The challenge problems based around them were pretty hard for me.

  • Muddiest point is nesting loops and how to implement

continue and break commands

  • I would love to go over more how to follow the code in

nested loops because sometimes I do not understand what gets read in what order.

28

slide-29
SLIDE 29

Nes Nested ed Loops

  • Print out the intersection of two lists

list1 = [‘lemon’, ‘orange’, ‘lime’] list2 = [‘banana’, ‘lemon’] for thing1 in list1: for thing2 in list2: if thing1 == thing2: print(thing1)

29

slide-30
SLIDE 30

Wh While loops (indefinite loops)

  • I was confused on while loops, specifically when they

should be used.

  • Roughly: used when you can't anticipate # of iterations
  • What does sentinel mean? Does it close out a loop?
  • Computer scientists use it to mean 'stopping symbol'

30

slide-31
SLIDE 31

Ex Exampl mple whi hile in n its s na natur ural ha habi bitat

new_list = [] while True: val = input("Enter a value or 'q' to quit\n") if val == 'q': break new_list.append(value) print(str(new_list))

31

slide-32
SLIDE 32

Us Using ng whi hile to iterate on n same me thi hing ng

num = 14 while num >= 1: print(num) num = num // 2 How many lines are printed: A) 3 B) 4 C) 5 D) 6 E) 7

32

slide-33
SLIDE 33

Ne Next week eek's s rea eading

  • Is a little lighter.
  • A little more theoretical depth on functions (4 sections)
  • Finish off zyBooks coverage of Excel (2 sections)
  • Additional readings on Excel's INDEX, MATCH, VLOOKUP

33