cs 105
play

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


  1. CS 105 Lecture 6: Loops Craig Zilles (Computer Science) https://go.illinois.edu/cs105sp20 March 2, 2020

  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

  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

  4. Sh Shor ort 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 is True True or anything() is False False and anything() • 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

  5. Wh What does this program output? print('hello') and print('there') • A) it raises an error • B) hello • C) there • D) hello there • E) it prints nothing, but raises no errors 5

  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

  7. Sh Shape of of "d "deci cision on tr tree": ": if w/o 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

  8. Sh Shape of of "d "deci cision on 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

  9. Ch Choos oosing 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

  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

  11. Nes Nesting When 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 = 10 else: sales_bonus = sales_bonus + 2 else: sales_bonus = sales_bonus + 1 Can I change the first 'else' into elif? 11

  12. Nes Nesting • CS likes composition; indent + indent = nesting Code Block A if condition1: Code Block B (Execution determined by condition1) if condition2: Code Block C (Execution determined by condition2) Code Block E (Same indentation as A) 12

  13. Which is Wh is no not a a va valid path through th this co code? Code Block A if condition1: Code Block B (Execution determined by condition1) if condition2: A) A, E Code Block C (Execution determined by condition2) B) A, B, E C) A, B, D, E Code Block D (Same indentation as B) D) A, B, C, D, E Code Block E (Same indentation as A) 13

  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

  15. Wh What does f(7) re return? def f(x): y = 9 if x <= 6 else -9 if x > y: A) -9 return y B) 7 return x C) 9 D) -9 then 7 E) 9 then 7 15

  16. An Annou ounce 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

  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

  18. Loop Loop con once 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

  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

  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

  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

  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

  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

  24. Wh What is the contents of ne new_l _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] 24

  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

  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!') How many lines of output will this print? A) 0 –or– there is an error B) 1 C) 4 D) 5 E) 6 26

  27. Us Using ng rang nge to get every y othe her cha har 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 27

  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

  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

  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

  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

  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

  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

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend