Discussion:
[Tutor] Help!
Fredrick Barrett
2015-05-15 23:35:30 UTC
Permalink
Hi, I'm a beginner and I've reached a roadblock. I'm trying to create a
simple guessing game program just to practice creating loops, however it is
not working out as planned.

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 ")

if guess == rand_value:
print ("Congratulations! You guessed it!")
while guess != rand_value:
input ("try again")
else:
print ("Sorry, you're wrong.")


input ("\n\nBetter luck next time. Press the enter key to exit.")

The goal is for the program to keep running until someone successfully
guesses the right number, however I think I've accidentally created an
infinite loop. Any help will be greatly appreciated.
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Steven D'Aprano
2015-05-16 02:08:09 UTC
Permalink
Post by Fredrick Barrett
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.
Post by Fredrick Barrett
print ("Congratulations! You guessed it!")
If you guessed correctly, the game ends.
Post by Fredrick Barrett
input ("try again")
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
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Continue reading on narkive:
Loading...