Skip to content Skip to sidebar Skip to footer

I'm Trying To Write A Number Guessing Game In Python But My Program Isn't Working

The program is supposed to randomly generate a number between 1 and 10 (inclusive) and ask the user to guess the number. If they get it wrong, they can guess again until they get

Solution 1:

Just move the congratulations message outside the loop. You can then also only have one guess input in the loop. The following should work:

while guess != number:
    if guess >= 1 and guess <= 10:
        print "Sorry, you are wrong."
    else:
        print "That is not an integer between 1 and 10 (inclusive)."

    guess = int(raw_input("Guess another number: "))

print "Congratulations! You guessed correctly!"

Solution 2:

The problem is that in a if/elif chain, it evaluates them from top to bottom. Move the last condition up.

if guess == number:
   ..
elif other conditions.

Also you need to change your while loop to allow it to enter in the first time. eg.

while True:
 guess = int(raw_input("Guess a number: "))
 if guess == number:
   ..

then break whenever you have a condition to end the game.


Solution 3:

The problem is that you exit the while loop if the condition of guessing correctly is true. The way I suggest to fix this is to move the congratulations to outside the while loop

import random


number = random.randint(1,10)

print "The computer will generate a random number between 1 and 10.   Try  to guess the number!"

guess = int(raw_input("Guess a number: "))


while guess != number:
    if guess >= 1 and guess <= 10:
       print "Sorry, you are wrong."
       guess = int(raw_input("Guess another number: ")) 
    elif guess <= 0 and guess >= 11: 
       print "That is not an integer between 1 and 10 (inclusive)."
       guess = int(raw_input("Guess another number: "))

if guess == number:
 print "Congratulations! You guessed correctly!"

Post a Comment for "I'm Trying To Write A Number Guessing Game In Python But My Program Isn't Working"