【问题标题】:"while True:" loop returns nothing after one cycle"while True:" 循环在一个循环后不返回任何内容
【发布时间】:2016-10-28 06:04:21
【问题描述】:

这就是问题所在:我的 while 循环根本不重复,它只是在 Python 启动器中返回一个空行并且不继续执行代码,我在最后添加了一个打印函数来检查它是否只是跳过。 我使用了几种方法让代码重复,例如While True:While 0 == 0,所以我开始认为代码中的其他地方存在问题。有问题的代码是:

while True:
 while i <= dice_amount:
   dice_output = random.randint(0,dice_range)
   print("dice number ", i, " is ", dice_output)
   i +=1
 while input_answer == "unknown":
   input_answer = input("would you like to throw the dice again? Y/N")
   if input_answer == "N":
    time.sleep(2)
    os.exit
   elif input_answer != "Y":
    input_answer = "unknown"

print("code is broken") #to see if code just skips loop

This 是我尝试重复时发生的情况 非常感谢您的帮助,我只想说我是编码新手,所以我知道它可能没有被优化,但是说我如何优化它的评论会很有帮助。

一开始变量的定义如下:

dice_amount = int(input("how many times would you like to roll the dice?"))
dice_range = int(input("how many numbers would you like on the dice?"))
input_answer = "unknown"
i = 1

【问题讨论】:

  • idice_amountinput_answer 定义在哪里?它们在循环之前的值是多少?
  • 抱歉,编辑了我的问题以表明这一点

标签: python loops while-loop python-3.5


【解决方案1】:

您需要在“while True”之后将 i 设置为 1,并在第二个内部循环之前将 input_answer 设置为“unknown”。更正代码:

while True:
 i = 1
 while i <= dice_amount:
   dice_output = random.randint(0,dice_range)
   print("dice number ", i, " is ", dice_output)
   i +=1
 input_answer = "unknown"
 while input_answer == "unknown":
   input_answer = input("would you like to throw the dice again? Y/N")
   if input_answer == "N":
    time.sleep(2)
    os.exit
   elif input_answer != "Y":
    input_answer = "unknown"

print("code is broken") #to see if code just skips loop

【讨论】:

  • 抱歉,忘记在我的问题中添加,现在在底部
  • 我看不出这有什么帮助,我在整个代码块之前都做了这两个?
  • 问题是如果你重新滚动。如果您选择重新滚动,则两个内部循环都不会再次运行,因为i 已经大于dice_amount 并且input_answer 已经是"Y"。在 while True 循环中初始化它们可以解决这个问题。
  • @Blckknght 谢谢,当输入 Y 时,我将代码更改为将 i 设置为 1,并创建了一个新变量 input_known 以消除问题。顺便说一句,据我所知,如果现在有新问题,我应该创建一个新问题
  • 一般来说,如果是新问题,应该单独提问。如果问题小到不足以保证提出新问题,那么您应该更新您的原始问题。
【解决方案2】:

在阅读了其他 cmets 和答案后,我终于意识到了这个问题,我想出了这个修复方法。首先,我意识到如果没有答案是 Y 或 N,我不需要使用 input_answer,我只是将其设为重复循环,如果既不是 Y 也不是 N,它只是重复了问题,Y 打破了循环并且N 结束程序。如果回复是 Y,我添加 i = 1 以便重复。

这里是固定代码:

import random
import time
dice_amount = int(input("how many times would you like to roll the dice?"))
dice_range = int(input("how many numbers would you like on the dice?"))
i = 1

while True:
 while i <= dice_amount:
   dice_output = random.randint(0,dice_range)
   print("dice number ", i, " is ", dice_output)
   i +=1
 while True:
   input_answer = input("would you like to throw the dice again? Y/N")
   if input_answer == "N":
    time.sleep(2)
    os.exit
   elif input_answer == "Y":
    i = 1
    break

【讨论】:

  • 老实说,我不知道如何让休息时间工作,以便它再次询问有多少数字等,但这不是我想要的,所以我认为这是一个足够的答案。 PS。请随时对此答案发表评论,说明如何让它再次提问
猜你喜欢
  • 2011-05-25
  • 2017-11-21
  • 2017-11-09
  • 1970-01-01
  • 2021-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
相关资源
最近更新 更多