<分区>
使用此 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: ")
<分区>
使用此 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 或 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.")
关于python - while循环测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44269404/