2017-05-30 86 views
1

我没有得到这个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

看起来''或'应该是'和'。 – Carcigenicate

+0

您输入的任何数字总是不等于1或2,因此条件总是成功。 – alexis

回答

4

一个数量总是不等于1或2,您可能需要使用and:使用not in

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: ") 

是更具可读性:

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.") 
+0

谢谢!你的解释是有道理的 – user3323799