loops ii warmup
play

Loops II Warmup Edit your loop from last time that asks for names - PowerPoint PPT Presentation

Loops II Warmup Edit your loop from last time that asks for names and prints the one earlier in the alphabet. Change the loop so the loop ends when the first name is "STOP." That is, the user should no longer have to explicitly


  1. Loops II

  2. Warmup • Edit your loop from last time that asks for names and prints the one earlier in the alphabet. Change the loop so the loop ends when the first name is "STOP." That is, the user should no longer have to explicitly answer the question, "Do you want to keep going?" (get code from website if you want) – Challenge: make it so the loop ends immediately after the first name is entered, if the first name is STOP.

  3. The test must be while test : something that is True or False. statement statement The indented statements are more statements… called the body of statement the loop. statement more statements…

  4. Statement test is True WHILE Statement Statement test is False Statement Statement Statement Statement

  5. • Pseudocode is an informal way of writing algorithms for humans to read (not computers!) • Illustrates the logic of an algorithm, but omits details that people can fill in automatically. • You get to make it up as you go along, as long as you (and other people) can easily understand it.

  6. • Instead of saying name = input("What is your name?") • Pseudocode might use a line that says name = ask user for name

  7. • Instead of saying if x >= 0 and x <= 100: print("$%.2f" % x) • Pseudocode might use a line that says if x is between 0 and 100: print x with 2 decimal places The point is to get your ideas down on paper quickly, so you can worry about programming details and exact syntax later.

  8. To write any while loop: 1. Write out pseudocode for what the loop does, explicitly repeating lines until you've repeated the code at least twice. 2. Include an "if" statement in your code that will be True if you want the loop to keep going. 3. Make sure the code repeats the "if" statement at least twice.

  9. To write any while loop: 4. Find the statements between consecutive "if" statements. These statements will become the body of the loop. 5. The "if" test will become the "while" test. 6. If there's anything before the first "if" test, it will go immediately before the while loop (outside of the body).

  10. Practice • Recall our postage looping program from last week: – Ask the user for the ounces of their package. – Calculate the postage and print a message with the dollar amount. – Ask the user if they want to keep going. • Edit this program so the program stops automatically when the postage calculated is zero (do not print the message with zero dollars).

Recommend


More recommend