Pythons while loop

Programming languages have lots of different ways of creating loops, but one of the simplest ways in Python is to use a while loop. Here's an example:

answer = while

,00P «Ohdtàoh no" f answer == "no": answer = input("Are

print("We're there!

This is what the loop looks like when you write it as a Python while loop. The code keeps asking the question "Are we there?" until the user types something other than no. This is what it looks like when it runs:

The loop body is just one line of Code this e*M>le>t the loo? body ¿an be -any lines of Code. Iteven include branches and other loops.

Python Shell

£.ilp rrtit r.hell Qphijg Gptmn«; Window1;

IicenBe[)" tor mire 1 ntorraa11 on. === HEHTMT ==================

L'ytfcon i.O.I (riUlifc'JSïfc, Fon Li ÜOUU, Miljilï] {ncn n.i.?] inn ilmn?

Type "copyright", "eradith"

Arr v^ thrra? tin Are we thsrei no Arft wr t.Vi^rrï nr> Are we tfiere? no Arc we thereÎ yea, at last J ore ' re the re 1

As soon as we type something other than "no , the loop body ends.

Did you notice that you had to set the value of the answer variable to something sensible before you started the loop? This is important, because if the answer variable doesn't already have the value no, the loop condition would have been false and the code in the loop body would never have run at all.

Bear that in mind. It might be useful in this next exercise...

change the game

ExsnciSe -

Now, it's time to apply your programming mojo. Be warned: this exercise is kind of tricky. You need to rewrite your game program so it keeps running until the user guesses the correct answer. You will need to use all of the things you've learned in this chapter. You will need to work out the conditions for each of the branches and loops that are required.

Remember: the program needs to keep asking the user for an answer while the current guess is wrong.

Hint: If you need to test that two things have different values, use the != operator.

This is the "not equal to" operator.

toaeV**

Reapy Bake

Reapy Bake

If you add these two lines of code to the top of your program:

from random import randint secret = randint(1, 10)

The secret variable will be set to a random number between 1 and 10. Modify your program from the facing page so that instead of the answer always being 5, it will instead use a random number from 1 to 10 as the answer.

Niable as "the eomct new game m

Exercise Solution

You needed to rewrite your game program so it keeps running until the user guesses the correct answer. You needed to use all of the things you've learned in this chapter. You needed to work out the conditions for each of the branches and loops that are required.

Hint: If you need to test that two things have different values, use the != operator.

Don t worry if your Code doesn't look e*act|y |ike th',s. The important thing is that i-t works in the same way when you run it.

the\oop print("WelCome!") guess = 0

print("WelCome!") guess = 0

M oi this code is indented wW* it's all '«side the U? Wy means g = input("Guess the number: ") guess = int(g) if guess == 5:

print("Too high") else:

print("T>o low") print("Game over'")

This part of the program is very similar to what you had before.

Reaps Bake

Reaps Bake

If you add these two lines of code to the top of your program:

from random import randint secret = randint(1, 10)

The secret variable will be set to a random number between 1 and 10. You were to modify your program from the facing page so that instead of the answer always being 5, it will instead use a random number from 1 to 10 as the answer.

from random import randint secret — randintfi, 10)

V-andom number-

printCWeltome!")

while guess !— secret1 Now, instead of checking if the 1 g .—. mput^uess . th.e . number:. .")..

answer's 5, we check it against the random number, which is held . guess - int(g)

in the "secret" variable. if guess —— secret. print("You win!") else.

if guess > secret.

printCToo . high")

else.

Tqst Drivq

So, what happens when you run the new version of your program?

Python Shell

£ile frtit '".h.pjl ftehug Gptmn«; Winrinwi

JJP'P

Tython 3.0.1 (rîDl:Ê555È, Feb 17 200Ü, 15:15:57) (GCC 4.Î.1I uii linu.i2

Type "copyright", "crcdita" or "liccnoo[)" for r.orc information.

-J» ============================ HISTMT ==================

ÎTII^^.I 1 liM rLLjr.b^r : ^ TOO High in : : M ! [LEirallhfC : —i

fill nil-1 HIV hf I

The program keeps asking for another guess for as long as you keep getting the answer wrong.

The direct answer is now a random number and it should be different each time you play the game program stops when Y0" ihe answer right

I rv 1ft Till dl

Your users love the program.

And you created it all yourself. By carefully analyzing the problem, deciding what the feedback needed to be, and working out the intricate looping and branching logic, you've created something that really rocks.

Well done. You're on your way to becoming a real code jockey.

Was this article helpful?

0 0

Post a comment