python - while循环测试

标签 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 或 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/

相关文章:

python - 使用 f 字符串作为模板

python - SciKit-learn 网格搜索自己的评分对象语法

php - 验证输入字符串不超过字数限制

excel - 如何在Excel中的多个工作簿的相同单元格中选择变量

c - 循环插入二叉树

python - 如何替换 Python 字符串中的单词

python - 带有 BS4 的简单蜘蛛神秘地将每个页面翻倍

javascript - 删除字符串中特定位置的字符 - javascript

java - 是否有用于 Java 字符串的 left() 函数?

javascript - 循环并打印时间列表