【问题标题】:While loop test [closed]While循环测试[关闭]
【发布时间】:2017-10-31 08:26:08
【问题描述】:

我没有通过这个 Python 代码得到想要的结果。需要帮助。

当您输入符合条件的字符串时,while 循环应该停止。

代码:

x = input("Enter input: ")

while (int(x[3]) != 1 or int(x[3]) != 2):
    print("The fourth character must be a 1 or 2")
    x = input("Enter input again: ")

【问题讨论】:

  • 看起来or 应该是and
  • 您输入的任何数字将始终不等于 1 或 2,因此条件始终成功。

标签: python string loops while-loop boolean


【解决方案1】:

一个数字总是不等于 1 或 2,你可能想使用and

x = input("Enter input: ")

while int(x[3]) != 1 and int(x[3]) != 2:
    print("The fourth character must be a 1 or 2")
    x = input("Enter input again: ")

使用not in 更具可读性:

x = input("Enter input: ")

while int(x[3]) not in (1, 2):
    print("The fourth character must be a 1 or 2")
    x = input("Enter input again: ")

如果您想要一种更容错的方式,请与字符串进行比较:

while True:
    x = input("Enter input: ")
    if x[3:4] in ('1', '2'):
        break
    print("The fourth character must be a 1 or 2.")

【讨论】:

  • 谢谢!你的解释很有道理
猜你喜欢
  • 1970-01-01
  • 2010-09-18
  • 2011-01-22
  • 1970-01-01
  • 2016-03-14
  • 1970-01-01
  • 2016-03-25
相关资源
最近更新 更多