Reputation: 13
I created a simple program in Python where I use the random number module to generate a random number between 1 and 10 then ask the user to guess the number as shown here:
import random
randnum = random.randint(1, 10)
guess = input("Guess a number between 1 and 10: ")
guess = int(guess)
while guess != randnum:
if guess < randnum:
print("Your guess is too low.")
guess = input("Guess again: ")
guess = int(guess)
elif guess > randnum:
print("Your guess is too high")
guess = input("Guess again: ")
guess = int(guess)
elif guess == randnum:
print("That is correct!")
My problem is getting the program to print the final elif statement when they guess the correct number. Instead the while loop terminates because the conditions have been met. How do I print out the final statement when the correct number has been guessed?
Upvotes: 0
Views: 176
Reputation: 1775
When the user gets it right, then guess != randnum
will be false and the loop will exit before looking at any options. Just move the last elif
outside the loop:
import random
randnum = random.randint(1, 10)
guess = input("Guess a number between 1 and 10: ")
guess = int(guess)
while guess != randnum:
if guess < randnum:
print("Your guess is too low.")
guess = input("Guess again: ")
guess = int(guess)
elif guess > randnum:
print("Your guess is too high")
guess = input("Guess again: ")
guess = int(guess)
print("That is correct!")
Although I would write code something more like this:
import random
randnum = random.randint(1, 10)
guess = int(input("Guess a number between 1 and 10: "))
while guess != randnum:
if guess < randnum:
print("Your guess is too low.")
elif guess > randnum:
print("Your guess is too high")
guess = int(input("Guess again: "))
print("That is correct!")
Upvotes: 3