[Tutor] while loops
Steven D'Aprano
steve at pearwood.info
Wed Dec 14 23:55:43 CET 2011
rog capp wrote:
[...]
> # Guessing loop
> while guess != the_number:
> if guess > the_number:
> print("Lowere...")
> else:
> print("Higher...")
> guess = int(input("Take a guess: "))
> tries += 1
>
> print("good job")
> input("\n\nPress the enter key to exit.")
>
>
>
> This is a program from "Python for the absulute beginner(which I am).
> End of the chapter is a challenge that asks me to limit the number of
> guesses the player gets.
> If he/she fails to guess the number after a certain number of attempts
> then it displays a message
> about his failure.It needs to be a while loop cause it the topic I'm
> at.Can anyone give me some help
You need a counter to count how many guesses are made. You already have a
variable counting the number of tries, so you are half-way there.
The loop condition currently is:
while guess != the_number
or in English:
"while the guess is not equal to the number: loop"
Still in English, you want to change the condition to:
"while the guess is not equal to the number and the number of
tries is less than the maximum number of tries: loop"
Translate that loop condition from English to Python, and you've got it.
Then, once you have the loop fixed, the final change needed is to change the
message printed at the end, outside the loop. Currently it unconditionally
prints "good job". You need to change that to only print "good job" if the
guess is equal to the number, otherwise print something else.
--
Steven
More information about the Tutor
mailing list