简体   繁体   中英

Python input validation?

I have a simple input validation code asking the user for either ACT or SAT.

test=input("Are you taking SAT or ACT?..")
while test!=("SAT" or "ACT"):
    print("error")
    test=input("Are you taking SAT or ACT?..")

It seems to work correctly for "SAT" which is in front on line 2, but not ACT! When I type in ACT in the module it will print "error" like it was false. What is my flaw here? Logic? Syntax? Semantic? What can I do to fix it?

Thank you.

I don't think that this statement is valid:

test!=("SAT" or "ACT")

You may use

test != "SAT" and test != "ACT"

Or use in operator:

test=input("Are you taking SAT or ACT?..")
while test not in ("SAT", "ACT"):
    print("error")
    test=input("Are you taking SAT or ACT?..")

The expression ("SAT" or "ACT") evaluates to "SAT" since it basically evaluates the OR operation on two strings. In order to fix the issue, this is what you can do:

while(1):
    test = input("Are you taking SAT or ACT")
    if test in ("SAT", "ACT"):
        break

    print("Error")

将条件从test!=("SAT" or "ACT")换成test==("SAT" or "ACT") ,也可以按照Kshitij Saraogi的解释使用IN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM