[Tutor] Help!
Steven D'Aprano
steve at pearwood.info
Sat May 16 04:08:09 CEST 2015
On Fri, May 15, 2015 at 07:35:30PM -0400, Fredrick Barrett wrote:
> print ("Lets play a game")
>
> import random
>
> # Generate random number from 1-10
> rand_value = random.randint(1,10)
> guess = input("Guess a number from 1-10 ")
Here you guess once.
> if guess == rand_value:
> print ("Congratulations! You guessed it!")
If you guessed correctly, the game ends.
> while guess != rand_value:
> input ("try again")
> else:
> print ("Sorry, you're wrong.")
You ask the user to try again, but you pay no attention to their reply.
You just completely ignore their guesses, apart from the very first one.
Also, and by the way, although Python does have a "while...else"
construct, it's a bit misleading and I don't think it is useful in this
case.
Experiment with something like this instead:
rand_value = random.randint(1,10)
guess = 0 # Guaranteed not to match.
while guess != rand_value:
guess = input("Guess a number between one and ten: ")
print("Congratulations!")
Notice that each time through the loop, I set guess to a new value?
--
Steve
More information about the Tutor
mailing list