【问题标题】:Stuck in while loop陷入while循环
【发布时间】:2017-03-05 14:57:46
【问题描述】:

我正在尝试为我的侄子制作掷骰子,这样他就可以在没有骰子的情况下玩棋盘游戏。即使我输入了一个正确的条件,我也陷入了一个while循环。我试图让他选择他想使用的骰子,但如果他选择了错误的骰子,那么它会要求他再次输入。我的代码是...

dice_select = input('Enter the amount of sides are on the dice you want to throw, either 4, 6, or 12:  ')
while dice_select != 4 or dice_select != 6 or dice_select != 12:
    dice_select = int(input('Sorry thats not quite right. Enter the amount of sides are on the dice you want to throw, either 4, 6, or 12:  '))

如果我输入 4、6 或 12,那么当它应该继续时,它仍然会让我进入循环。

【问题讨论】:

  • 条件为假的唯一方法是dice_select 同时等于 4、6 和 12。
  • 重新阅读您的情况。根据您寻求的价值对其进行评估。当dice_select4 时会发生什么?

标签: python loops while-loop numbers int


【解决方案1】:

试试这个:

    dice_select = int(input('Enter the amount of sides are on the dice you want to throw, either 4, 6, or 12:  '))
    while not (dice_select == 4 or dice_select == 6 or dice_select == 12):
        dice_select = int(input('Sorry thats not quite right. Enter the amount of sides are on the dice you want to throw, either 4, 6, or 12:  '))

这意味着循环直到 dice_select 等于 4、6 或 12。

在您的程序中,您的 while 循环条件始终为真,因为当它等于 4 时,您的程序正在检查 false 或 true 或 true,这将始终为 true。

换句话说,您的程序正在寻找 dice_select 同时等于 4,6 和 12 的时间。这是不可能的。

【讨论】:

  • 输入您要掷的骰子的边数,4、6 或 12:12 抱歉,这不太对。输入您要掷的骰子的面数,4、6 或 12:12 您选择掷 12 面骰子,结果为 1
  • 因为在您的第一个语句中您没有将输入转换为整数,所以您将比较字符串和整数,这在 python 中总是错误的。我将编辑上面的代码以反映这一点。
猜你喜欢
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多