Hardware Reference
In-Depth Information
while Statement
Let's look at an example while loop. Type the following code and run it. It will loop and keep
printing an insult until you type no .
userAnswer=””
while (userAnswer!=”no”):
printInsult(“Eric”,20)
userAnswer = raw_input(“can you take any more?”)
!= means not equal, so the while loop repeats whilst the variable userAnswer is not equal to
no . After printing an insult the code gets input from the user and updates the userAnswer
variable ready for the test before the start of the next loop.
raw_input was renamed input in Python 3.
TIP
Consider what the loop would look like if you didn't create a function - you'd have to include
all the code inside the loop body. This makes the code harder to read, and means you'd have
to retype it in each of these examples!
If your program gets stuck in an infinite loop , a loop that never ends, you can stop your program
by pressing Ctrl + C.
TIP
Putting It All Together
You should now have a program that generates a torrent of insults! This appendix has cov-
ered the basics. Look at each line and see if you understand what each part does before run-
ning the program. Then, to personalise your program, you could make it produce different
insults depending on the user's name. For example, you could make it say something nice
only if your name is entered, or you could change the number of insults it generates depend-
ing on the user or their age (such as a younger brother). You could print “really old” for peo-
ple over a certain age, or if you're clever¸ you could use a loop to print an additional “really ”
for every decade someone has been alive.
The main thing is to not be afraid of changing things to see what happens. Just as you can't
learn to paint without practicing, you won't learn how to program without experimenting.
hroughout this topic, there are ideas to change the projects to make them your own and to
make the computer do what you want it to do.
 
Search WWH ::




Custom Search