【问题标题】:validating an input not working properly (python)验证输入无法正常工作(python)
【发布时间】:2022-08-13 13:57:58
【问题描述】:
serviceType = \"\"

while serviceType != \"R\" or serviceType != \"P\":
    serviceType = input(\"Service type (R/P): \").upper()
    print(serviceType)
    if serviceType != \"R\" or serviceType != \"P\":
        print(\"Error: Invalid Entry \\n\")

每当我运行上面的代码时,无论我输入什么,输出都是消息“错误:无效条目”。有什么我做错了吗?

    标签: python


    【解决方案1】:

    if 条件中的条件之一始终是True,因此您总是会收到错误消息。

    尝试这个:

    serviceType = ""
    
    while serviceType != "R" and serviceType != "P":
        serviceType = input("Service type (R/P): ").upper()
        print(serviceType)
        if serviceType not in ["R", "P"]: # <- line changed
            print("Error: Invalid Entry \n")
    

    【讨论】:

    • 或者更简单,只需在if 语句中将条件从or 更改为and + 如果您假设在serviceType"R" 时需要退出循环,则对while 循环执行相同操作或"P"
    • 我也不相信这行得通。它不再打印出错误消息,但它也只是一遍又一遍地重新运行相同的代码
    • 根据@Alex.Kh 的建议更改了代码。
    • 实际上等待 Alex.Kh 的回应奏效了。谢谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    相关资源
    最近更新 更多