简体   繁体   English

Python输入验证?

[英]Python input validation?

I have a simple input validation code asking the user for either ACT or SAT. 我有一个简单的输入验证代码,要求用户输入ACT或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! 它对于第2行前面的“ SAT”似乎正常工作,但不起作用! When I type in ACT in the module it will print "error" like it was false. 当我在模块中输入ACT时,它将显示“错误”,就像它是错误的一样。 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: in运算符中使用:

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. 表达式("SAT" or "ACT")计算结果为"SAT"因为它基本上计算两个字符串上的OR运算。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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