简体   繁体   中英

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 it right. If they guess right, the program is supposed to congratulate them.

This is what I have and it doesn't work. I enter a number between 1 and 10 and there is no congratulations. When I enter a negative number, nothing happens.

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: "))
   elif guess == number:
     print "Congratulations! You guessed correctly!"

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM