q and a for section 5.1 cs 106, fall 2014. while loop syntax q: the syntax for a while statement is:...

31
Q and A for Section 5.1 CS 106, Fall 2014

Upload: jaidyn-hawthorn

Post on 15-Dec-2015

224 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

Q and A for Section 5.1

CS 106, Fall 2014

Page 2: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

While loop syntax

Q: The syntax for a while statement is:while _______________ : _____________ A: while <boolean expression>: <body>

or, condition

Page 3: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

Difference from for loop

Q: How often does a while loop execute its <body>?

A: until the boolean condition is False.

Note: that’s how it differs from for loop.

Page 4: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

while loop vs. for loop

Q: When would you use a while loop instead of a for loop?

A: When you don't know how many times you need to run the body of the loop.

For loop is definite iteration; while loop is indefinite iteration.

Page 5: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

Changing the condition

Q: Suppose you have a while loop like this:while var1 <op> var2: <body>Is it good/bad/ugly to alter the value of var1 or var2 in the body of the loop?A: You almost *always* alter the value of var1 or var2 in the body, or you would have an infinite loop.

Page 6: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

while loop vs. index-based for loop

for i in range(len(data)): use data[i] in body

i = 0while i < len(data): use data[i] in body i = i + 1

Page 7: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

Q: Thwarting an infinite loop

Q: How would we make sure the following code does not run forever (without changing do_stuff() or update_x())?

while some_cond(x):do_stuff()x = update_x(x)

Page 8: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

A: Thwarting an infinite loop

num_runs = 0while some_cond(x) and num_runs < 10000:

do_stuff()x = update_x(x)num_runs += 1

Page 9: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

Checking for item in list (p 162)

Q. What is bad about this loop (where you search for item val in list data)?found = Falsefor item in data: if item == val: found = TrueA. Continues searching even after the item is found.

Page 10: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

Checking for item in list (p 162)

Q. What is bad about this loop (where you search for item val in list data)?for item in data: if item == val: found = True else: found = FalseA. It is wrong! If you find an item but there are more items, you “reset” found to False.

Page 11: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

Checking for item in list (p 162)

Q. Why have i < len(data) in this code?i = 0found = Falsewhile i < len(data) and not found: if data[i] == val: found = True else: i = i + 1A. This is index-based search. You have to make sure i does not “go off” the end of the list, if val is not in the list.

Page 12: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

While loops and user input

Q: What is bad about this code?guests = []name = raw_input(“Enter a name (blank to end): “)while name != “”: guests.append(name) name = raw_input(“Enter a name (blank to end): “)print “You entered”, len(guests), “guests.”

A: The line name = raw_input… has to be written twice…

Page 13: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

While loops and user input (2)

Q: What is bad about this fix?guests = []name = ‘fake’while name != “”: name = raw_input(“Enter a name (blank to end): “) if name != “”: guests.append(name)print “You entered”, len(guests), “guests.”

A: We are now testing the “stop condition” twice!

Page 14: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

While loops and user input (3)

Q: What is wrong with this fix?guests = []name = ‘fake’while name != “”: name = raw_input(“Enter a name (blank to end): “) guests.append(name)print “You entered”, len(guests), “guests.”

A: We are now inserting the empty string at the end of the guests list. Fix by addingguests.pop() before the print statement.

Page 15: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

While loops and user input (4)

Best solution: use break (duh!)

guests = []while True: name = raw_input(“Enter a name (blank to end): “) if name == “”: break guests.append(name)print “You entered”, len(guests), “guests.”

Using break in this manner allows you to do a “mid-loop” test. Otherwise, we can only do “pre-loop” test.

Page 16: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

Rewrite this codenumber = 0while not 1 <= number <= 10: number = int(raw_input(“Enter a single digit: “)) if not 1 <= number <= 10: print ‘Your number is not a single digit.’

Page 17: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

Rewrite this code: Answerwhile True: number = int(raw_input(“Enter a single digit: “)) if 1 <= number <= 10: break else: print ‘Your number is not a single digit.’

Page 18: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

What is wrong with this code?

while i < j: # or a for statement someCode() someMoreCode() if some_condition(): break continue

A: Don’t need continue at the end of a loop body – it will go back to the top anyway!

Page 19: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

Efficiency

Q: Are there instances where while loops are always more efficient than if statements?Which is more efficient: while loops or for loops?

A: while and if are different (although syntactically very similar). while is a loop; if is a single test.for and while have generally the same efficiency.

Page 20: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

Why don’t the authors like break/continue?

A: The authors are, perhaps, purists. It *is* nice to be able to look at a loop and know that you enter it from the top, and exit it when the loop is all done (for) or the condition is False (while). If you have break in the middle, you create another “exit point”. There is a branch of CS where you try to prove that code is correct, with pre-conditions, mid-conditions, post-conditions, etc. That goes out the door with break.

Page 21: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

Old Slides

Page 22: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

continue statement

• Used only within a loop body– in loop body itself, or within a body within the

loop body.– for while loops and for loops.

• Makes control go back to the top of the loop.• Often used when code detects that nothing

else needs to be done with the current element of the loop.

Page 23: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

One use of continue: to filter# Plot each earthquake, skipping comment lines# and the header line. for line in input_lines: fields = line.split() if len(fields) == 0: # skip blank line continue if fields[0].startsWith("#"): # skip comment lines continue if fields[0] == 'Src': continue # do stuff with fields.

Page 24: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

break statement

• also used only in loop body -- for loop or while loop.

• causes control to pass to first line after end of loop body.– i.e., you "break" out of the loop.

• useful for when searching through a sequence until you find what you are looking for.

• allows you to make a “mid-loop test”.

Page 25: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

Mid-loop test

• while statement is pre-loop test• Other languages have post-loop test:repeat: do_stuff()until <bool expr is False>

• Using while True and break, you can do mid-loop test. (Useful for getting user input.)

while True: do_stuff() if <bool expr>: break do_other_stuff()

Page 26: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

Example of use of break# find if num is a prime

isPrime = True # assume it is primefor div in range(2, num / 2 + 1): if num % div == 0: # divides with no remainder # found a divisor so num is not prime isPrime = False break# isPrime is True mean num is a prime number.

Page 27: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

Example of use of break

# looking for first room with someone in it.

found = Falsefor room in rooms: if not room.is_empty(): found = True breakif found: room.invite_to_dance_the_night_away()

Page 28: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

Practice while loops

Problem: Convert the following into an index-based loop:for g in groceries: print gAnswer:for i in range(len(groceries)): print groceries[i]

Page 29: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

Practice while loops

Problem: Convert the following into a while loop:for g in groceries: print gAnswer:i = 0while i < len(groceries): print groceries[i] i += 1

Page 30: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

Average of numbers

Problem: write code to prompt the user for a number, until the user enters “q”. When the user enters “q”, print the average of the numbers that were entered.

Page 31: Q and A for Section 5.1 CS 106, Fall 2014. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while :

Average of numberstotal = 0numNums = 0while True: num = raw_input(“Enter a number, q=quit:”) if num == “q”: break total += float(num) numNums += 1if numNums == 0: print “No numbers entered”else: print “Average is “, float(total) / numNums