python - 如何调试 "guessing number"游戏中的错误结果?

标签 python python-3.x loops if-statement while-loop

由于某种原因,即使我得到正确的答案,“正确答案”也不会被打印。我不知道为什么。

import random
y = random.randint(1,6)

start_game = input("Pick a number between 1 and 6")


while start_game != y:
  if start_game  > y:
    print("guess too high")
    start_game = input("Pick a number between 1 and 6")
  elif start_game < y:
    print("guess too Low")
    start_game = input("Pick a number between 1 and 6")
  else:
    print("correct guess")`

最佳答案

在检查 if, elif, else 之前先退出 while 循环健康)状况。 您检查的第一件事是 while 循环的条件,如果 y = start_game 则退出它。您将无法达到 else 条件。

将 while 循环后的打印内容移出循环。

您还需要将输入的返回值转换为 int。

这样:

    import random
    y = random.randint(1,6)

    start_game = int(input("Pick a number between 1 and 6"))


    while start_game != y:
      if start_game  > y:
        print("guess too high")
        start_game = int(input("Pick a number between 1 and 6"))
      elif start_game < y:
        print("guess too Low")
        start_game = int(input("Pick a number between 1 and 6"))
    print("correct guess")

事情是,它会进入循环,首先检查循环的条件,然后它会检查 if 语句,但是,一旦条件之一为 true,if、elif、else 检查就会停止,这意味着 for例如,即使 y < start_game ,您将要求另一个输入,但由于您输入了 if,因此不会检查 elif 和 else 条件,从而导致循环结束,然后它会返回检查循环的条件等。

关于python - 如何调试 "guessing number"游戏中的错误结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49879874/

相关文章:

python - 将 namedtuple 的 __str__ 和 __repr__ 行为引入常规类

python - Jupyter不会在当前目录下创建新的笔记本

python - Tkinter 函数 "root.after()"不运行指定的函数

linux - 遍历文件并用 sed 替换每一行

python - 如何在 Python 中的非打印 ascii 字符处拆分行

python - Project Euler #18 - 如何使用 Python 暴力破解树状结构中的所有可能路径?

python - 通过 ctypes 从 Python 调用 C 代码,使用 python 对象列表

python-3.x - Python 中 Matplotlib 中的响应式文本

java - 基本增量

bash - 在 bash shell 中添加文件大小