Top Banner
Lecture 5: Loops Craig Zilles (Computer Science) September 26, 2019 https://go.illinois.edu/cs105fa19 CS 105
27

L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019 CS 105

Jul 01, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

Lecture 5: Loops

Craig Zilles (Computer Science)

September 26, 2019

https://go.illinois.edu/cs105fa19

CS 105

Page 2: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

Are you sitting next to someone to talk to for the clicker

questions?

Today I'm using: pythontutor.com

2

Page 3: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

Big Picture (Muddiest Points)• I felt that overall, this chapter is harder than the

previous chapters so I was very confused in general.• I didn't completely understand the concept of using

while and for loops. I will be honest, the more we are learning, things are coming more clearer about coding, but everything makes more sense after lecture.

• It felt like I could never get the answer on my own, but when I pressed 'show answer' and saw what to do it made sense. What can I do so I skip that step?

• in the participation activites, why does the answer sometimes have indents and other times it does not?

3

Page 4: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

Today1. Conditionals

• if, elif, else• Nesting

2. Looping: conditions, body, iteration3. for Loops (definite loops)4. range5. while Loops (indefinite loops)6. break and continue7. Loop Patterns

• Count, Sum• Find, Find Best

4

Page 5: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

Design of 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?

5

Page 6: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

Shape of "decision tree": if w/o elseAsked 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)

6

Page 7: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

Shape of "decision tree": if w/elseCompany 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)

7

Page 8: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

Choosing between many alternativesFinal 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'

8

Page 9: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

NestingWhen to use elif and when to use else? I think there should be only 1 else in the whole program but I saw:

if sales_type == 2:if sales_bonus < 5:

sales_bonus = 10else:

sales_bonus = sales_bonus + 2else:

sales_bonus = sales_bonus + 1

Can I change the first 'else' into elif?9

Page 10: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

Nesting• CS likes composition; indent + indent = nesting

10

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)

Page 11: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

Which is not a sequence of blocks?

A) A, EB) A, B, EC) A, B, D, ED) A, B, C, D, E

11

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)

Page 12: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

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.

12

Page 13: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

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

loop conditionloop body(one or more statements)

post-loop stuff

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

13

Page 14: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

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

14

Page 15: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

How many lines will be printed?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 errorB) 1C) 2D) 3E) 4

15

Page 16: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

How many lines will be printed?things = [22, [33, 44], 55, [66]]

for thing in things:

print(str(thing))

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

16

Page 17: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

Announcements

• Be sure to complete Spatial Post-Test

• Quiz 1 live now; finish by Saturday night

• Exam 1 next week; will be quite similar to Quiz 1

17

Page 18: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

Unpacking• 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

18

Page 19: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

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

19

Page 20: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

What is the contents of new_list?orig_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]

20

Page 21: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

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

21

Page 22: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

Using range to repeat fixed # of times

for i in range(5): # note that i not used

print('CS 105 is lit!')

22

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

Page 23: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

Using range to get every other char

orig_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

23

Page 24: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

Loop nesting• 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.

24

Page 25: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

Nested 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)

25

Page 26: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

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'

26

Page 27: L5 Loops - University Of IllinoisLecture 5: Loops Craig Zilles (Computer Science) September 26, 2019  CS 105

Example while in its natural habitatnew_list = []

while True:

val = input("Enter a value or 'q' to quit\n")

if val == 'q':

break

new_list.append(val)

print(str(new_list))

27