On the next line type four spaces and then type the action you want repeated like this

3. while number of bottles > 0:

4. print number of bottles, "bottles of beer on the wall"

If you add more lines, be sure to indent them.

Tip A while loop is useful in a program that waits for user input. The program in Listing 10-3 reports on the results of several "coin tosses." The while loop checks whether the user has asked to quit the program. Listing 10-3: Coin toss program_

import random

headcount = tailcount = 0

userinput = ''

print "Now tossing a coin..."

while userinput.lower() != "q":

flip = random.choice(['heads', 'tails'])

if flip == 'heads':

headcount += 1

print "heads! the number of heads is now %d" %

headcount

else:

tailcount += 1

print "tails! the number of tails is now %d" %

tailcount

print "Press 'q' to quit",

userinput = raw input("or another key to toss

again:")

print "the total number of heads:", headcount

print "the total number of tails:", tailcount

Was this article helpful?

0 0

Post a comment