循环测试

时间:2017-05-30 18:28:44

标签: python string loops while-loop boolean

我没有使用此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: ")

1 个答案:

答案 0 :(得分:4)

数字始终不等于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.")
相关问题