【问题标题】:Storing random integer存储随机整数
【发布时间】: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 语句放在函数中(除非您确定需要这样做)。将它们放在它们所属的脚本开头。

标签: python random numbers


【解决方案1】:

那是因为您在每个 if 语句中调用了self.game(),这会将执行流程带回到函数的开头,并且每次使用answer = random.randint(0, 1000) 都会生成一个新数字。

所以只需删除self.game() 并让函数结束:

import random

def game(self):
    answer = random.randint(0, 1000)
    while True:
        guess = int(input("Your tip is:"))
        if guess < answer:
            print ("Your tip is lower, than the answer! Try again.")
        elif guess > answer:
            print ("Your tip is bigger than the answer! Try again.")
        elif guess == answer:
            print ("Good job! You have found the answer!")
            self.replay()
            break

编辑 1:

您还应该在while 循环内移动用户输入他的猜测的行,以便用户可以猜测直到他得到正确的答案。我还添加了break 语句以在他得到正确答案时退出循环,而不仅仅是打印语句。你可以阅读更多关于breakhere的信息(上面的答案代码现已更新)

编辑 2:

另一个小细节,因为您是 Python 新手:您应该将所有导入语句放在 Python 模块的顶部,这是您应该遵循的 Python 编码指南,以使您的代码更清晰。你可以阅读更多here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-13
    • 2018-05-14
    • 1970-01-01
    • 2016-06-05
    • 2018-01-28
    • 1970-01-01
    • 2015-08-15
    相关资源
    最近更新 更多