1 / 19

Q and A for Section 5.1

Q and A for Section 5.1 . CS 106, Fall 2012. While loop syntax. Q: The syntax for a while statement is: while _______________ : _____________ A: while <boolean expression>: <body>. or, condition. Difference from for loop.

lynton
Télécharger la présentation

Q and A for Section 5.1

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Q and A for Section 5.1 CS 106, Fall 2012

  2. While loop syntax Q: The syntax for a while statement is: while _______________ : _____________ A: while <boolean expression>: <body> or, condition

  3. 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.

  4. 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.

  5. Newton’s Method getSqrtOf = float(raw_input(“Enter a number: “)) # Set oldEst and newEst to any initial values oldEst = 1.0 newEst = 4.0 # while last 2 estimates are quite different while abs(newEst - oldEst) > 0.0000001: # store previous estimate in oldEst oldEst = newEst # compute a new estimate and print it newEst = (oldEst + getSqrtOf/ oldEst) / 2.0

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

  7. A: Thwarting an infinite loop num_runs= 0 while some_cond(x) and num_runs < 10000: do_stuff() x = update_x(x) num_runs += 1

  8. 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.

  9. 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.

  10. 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”.

  11. Mid-loop test • while statement is pre-loop test • Other languages have post-loop test: repeat: do_stuff() until <boolexpris False> • Using while True and break, you can do mid-loop test. (Useful for getting user input.) while True: do_stuff() if <boolexpr>: break do_other_stuff()

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

  13. Example of use of break # looking for first room with someone in it. found = False for room in rooms: if not room.is_empty(): found = True break if found: room.invite_to_dance_the_night_away()

  14. Practice while loops Problem: Convert the following into an index-based loop: for g in groceries: print g Answer: for i in range(len(groceries)): print groceries[i]

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

  16. More practice: robots and obstacles Problem: Given a function seeObstacle() that returns True when an obstacle is in front of a robot, write an algorithm to have the robot detect and print out distance to the 8 obstacles around it at N, NE, E, SE, S, SW, W, NW.

  17. More practice: robots and obstacles Solution: for dir in range(8): # 8 directions dist = 0 while not seeObstacle(): goForward(5) # cm. dist += 5 print “distance is”, dist goBackward(dist) turnRight(45) # degrees

  18. 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.

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

More Related