{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

python07.html - CHAPTER 7 Iterations or Loops we'll do...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
CHAPTER 7 Iterations or Loops we'll do exercises in this chapter by table repeat a piece of code any number of times repeat: a number of times (e.g. repeat this 1000 times) repeat until something happens (e.g. read next line until file is empty) repeat while something is true (e.g. repeat as long as i is less than 5) while flow chart this is the kind of construct for which people in the far away past would have used gotos (jump from one place of the code to another) while loop while01.py num = 1 print("num (before while loop) is: ",num) while num <= 5: #this point is reached only if num <= 5 print("num is: ",num) num += 1 #this point is reached only if num > 5 print("num (after while loop) is: ",num) print("done") Exercise1 Change the code of while01.py so that it prints the numbers 1, 3, 5, 7, and 9. Exercise2 Change the code of while01.py so that it prints the numbers 2, 4, 6, 8, and 10 listing0702.py from pcinput import getInteger total = 0 count = 0 while count < 5: total += getInteger( "Please give a number: " ) count += 1 print( "Total is", total )
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
print( "The user entered", count,"numbers" ) Exercise3 Change the code block above so that it not only prints the total, but also the average of the five numbers. Exercise4 The first example of code of this chapter (p 65) also asks the user for five numbers, and prints the total. However, that code uses "Number x: " as a prompt, whereby x is a digit. Can you change that code so that it also uses such a changing prompt to ask for each number? listing0703.py from pcinput import getInteger num = -1 total = 0 print( "this program will ask you to enter a number until you enter 0" ) print( "when you enter 0 the program ends" ) while num != 0: num = getInteger( "Enter a number: " ) total += num print( "Total is", total ) ugly problems: the -1 the 0 is still added at the end (what if I wanted to end the loop using a different number) listing0704.py from pcinput import getInteger num = getInteger( "Enter a number: " ) total = 0 while num != 0: total += num num = getInteger( "Enter a number: " ) print( "Total is", total ) new ugly problem: repetition of the getInteger() function repetition is never good Exercise5 Create a loop that lets the user enter some numbers until he enters zero, and then prints their total and their average. Make sure you test the loop with no numbers entered, and with several copies of the same number entered.
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}