【发布时间】:2017-11-23 17:17:22
【问题描述】:
我最近开始使用 Python 编程。现在我正在做一个数字猜谜游戏。我对了解存储随机数的工作原理有疑问。我在这里环顾四周,找到了一些答案,但无法使其工作。代码工作正常,但我的答案(随机数)总是不同的,所以不可能猜到。 如果有人可以帮助我或改进我的代码,我会很高兴。 这是我拥有的代码的一部分:
def game(self):
import random
answer = random.randint(0, 1000)
guess = int(input("Your tip is:"))
while True:
if guess < answer:
print ("Your tip is lower, than the answer! Try again.")
self.game()
elif guess > answer:
print ("Your tip is bigger than the answer! Try again.")
self.game()
elif guess == answer:
print ("Good job! You have found the answer!")
self.replay()
【问题讨论】:
-
不要在
while循环内调用self.game(),让它循环。并将guess =行移动到循环中。 -
将包含
input的行移到while循环的开头,而不是调用self.game()使用continue,并在break之后使用self.replay()。跨度> -
请不要将
import语句放在函数中(除非您确定需要这样做)。将它们放在它们所属的脚本开头。