Here's a code example of a while loop. You can refer to it for ideas.
In [5]:
count = 0
while (count < 5):
print "Still going! ", count
count = (count + 1)
print "All done!"
Sally wants a program that counts backwards from 10 down to 0. Use a while loop to write the program.
In [ ]:
Sami wants a program that counts upwards from 0 to 100 by 5's (so it prints 0, 5, 10, 15, 20, and so on). Write the program using a while loop.
In [ ]:
Juna wants a program that takes a list of student names, and prints each name after it's entered. The program should keep running until "quit" is entered. Write the program using a while loop.
In [ ]:
Here's an example of how to append text to a text variable. This is helpful if you want to print several things on one line, without the computer going to a new line in between.
In [12]:
text = "Hello, "
text = text + "Jenny. "
text = text + "How are you today? "
print text
Tonya wants a program that prints a bar graph. If the user types in 4, then the program should print 4 # marks like this: #### If the user types in 5, it should print 5 hash marks in a row, and so on. Whatever number the user types in, the program prints one line with that many hashes in it, and then ends. The user only enters one number each time. Write the program.
In [ ]:
Tonya likes your bar graph program. Now she wants a variant of it where the user keeps entering numbers, and each time they do, the program prints a bar graph that many hashes wide.
You can write this by putting a while loop inside another while loop. Pay close attention to the indentation here. Write the program.
In [ ]:
In this final challenge exercise, you'll write an interactive game. Think carefully about what goes before the loop (set up process), what goes inside the loop (game play), and what goes after the loop (finishing).
The computer will come up with a random number between 1 and 20. The player will try to guess the number. The computer will tell them whether they should guess higher, guess lower, or if they got it.
The player gets as many guesses as they want to try to guess the secret number. Here's a sample run:
Welcome to Guess My Number!
I'm thinking of a secret number from 1 to 20. What is it?
Guess: 10
My secret number is higher.
Guess: 15
My secret number is lower.
Guess: 12
My secret number is higher.
Guess: 13
You got it!
You win.
In [10]:
# Here's how you make the computer come up with a secret number.
# First we need the helper code that makes random numbers (just once).
import random
# Each time we want a new random number, we call this.
secret = random.randrange(1, 20)
# Let's see what it chose.
print secret
In [ ]:
In [ ]:
In [ ]:
In [ ]: