【问题标题】:While loop / if statement combined with user input PYTHON [closed]While循环/if语句与用户输入PYTHON相结合[关闭]
【发布时间】:2016-06-07 17:37:22
【问题描述】:

用户应该能够在随机(介于 0.2 和 0.5 之间)疾病因子和输入自己的疾病因子之间进行选择。我尝试使用 while 循环将其关闭,然后使用 if 语句来选择 Y 或 N。但是一旦设置了疾病值,它就不再适用于原始的 Y 或 N 疾病因子标准,因此再次循环并询问用户是否要输入自己的疾病因子。我知道为什么会出错,但我不知道该放什么。

另外当用户选择“N”时,有错误提示

while random_disease < 0.2 or random_disease > 0.5 :
TypeError: unorderable types: str() < float()

我不明白为什么会出现这种情况,因为我最初将 random_disease 设置为一个数字,并且它在关于数字的循环中,而不是 Y 或 N。

对预设的缩进感到抱歉,它直接取自我当前的代码,其中包含许多循环、函数等。 有什么帮助吗?

# Random disease factor #
        random_disease = 12
        while random_disease != "Y" or random_disease != "N":
            random_disease = input("Do you want a random disease factor? Enter Y if you do, or N if you want to select it yourself. Remember this will be between 0.2 and 0.5")
            if random_disease == "Y":
                random_disease = random.uniform(0.2, 0.5)
            elif random_disease == "N":
                while random_disease < 0.2 or random_disease > 0.5 :
                    try:
                        random_disease = float(input("What is your selected disease factor? Remember this should be between 0.2 and 0.5 : "))
                    except ValueError as ex:
                        print(ex)
            print("Your disease is ", random_disease)

【问题讨论】:

  • 如果您想象一下代码的流程,当 while 循环将它评估为字符串时,您似乎正在将 random_disease 重置为浮点数。因此,即使您输入 Y/N,它也会被数字类型覆盖。解决方案是创建 while 循环评估的另一个变量:例如:while ask != 'Y' and ask != 'N'
  • 查看您的解决方案和有意义的代码 - 为整个循环设置一个变量真的行不通!我再次尝试了您的建议,现在效果很好。非常感谢。我无法选择您的评论作为解决方案,您能否将其(或其他内容)复制并粘贴到其他部分,以便帖子获得更好的评价?谢谢

标签: python if-statement random while-loop


【解决方案1】:

如果您想象一下代码的流程,当 while 循环将它评估为字符串时,您似乎正在将 random_disease 重置为浮点数。因此,即使您输入了 Y/N,它也会被数字类型覆盖。解决方案是创建 while 循环评估的另一个变量:例如:while ask != 'Y' and ask != 'N'

【讨论】:

    【解决方案2】:

    你有一个逻辑问题。您的 while 语句将始终为真;如果random_disease 是“Y”,则不会是“N”,反之亦然。你需要and,而不是or

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-05
      • 2013-04-20
      • 2015-05-19
      • 2013-06-09
      • 2014-01-21
      • 2015-11-08
      • 2016-01-12
      相关资源
      最近更新 更多