我正在尝试在python中编写一个数字猜谜游戏,但我的程序无效

时间:2015-11-07 19:12:31

标签: python python-2.7

该程序应该随机生成1到10之间的数字(包括1和10)并要求用户猜测该数字。如果他们弄错了,他们可以再次猜测,直到他们做对了。如果他们猜对了,该程序应该祝贺他们。

这就是我所拥有的,它不起作用。我输入1到10之间的数字,没有祝贺。当我输入负数时,没有任何反应。

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

3 个答案:

答案 0 :(得分:2)

只需在循环外移动祝贺消息即可。然后,您也可以在循环中只有一个猜测输入。以下应该有效:

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

答案 1 :(得分:0)

问题是在if / elif链中,它从上到下评估它们。 移动最后一个条件。

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

此外,您需要更改while循环以允许它在第一次进入。例如

while True:
 guess = int(raw_input("Guess a number: "))
 if guess == number:
   ..
只要你有条件结束游戏,

就会中断。

答案 2 :(得分:0)

问题是如果正确猜测的条件为真,则退出while循环。我建议解决这个问题的方法是将祝贺移到while循环之外

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