【发布时间】:2015-11-07 19:12:30
【问题描述】:
该程序应该随机生成一个介于 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!"
【问题讨论】:
-
你是如何生成
number的? -
首先,while 循环中的所有内容都取决于猜测是否错误。然后在其中,如果第一个
if条件匹配(即如果guess在 1 和 10 之间),则告诉玩家他们错了。这将阻止猜测正确的情况。 -
把祝贺移到while循环外,去掉最后一个elif
-
guess <= 0 and guess >= 11永远不能是True。你需要guess <= 0 or guess >= 11
标签: python python-2.7