Python : 验证用户的输入?

Python : verifying user's input?

我的变量userAnswerList[]接收用户的输入,我需要验证用户是否输入了ABC、[=16以外的输入=].

下面是我的代码,想知道我应该如何验证用户在 (A B C D) 范围内的输入,如果不打印错误信息?

answerList = ["A","C","A","A","D","B","C","A","C","B","A","D","C","A","D","C","B","B","D","A"]
userAnswerList = []
correct = 0
incorrect = 0

def main():
    for i in range(20):
        i = i + 1
        answer = input("Please Enter the answer for Question %d:" %i)
        userAnswerList.append(answer)
        numCorrect = [i for i in userAnswerList if i in answerList]

    if len(numCorrect) > 15:
        print("Congratulations You have passed the exam!")
    elif len(numCorrect) < 15:
        print("Failed....Please try again")

correct = len(numCorrect)
incorrect = 20 - correct

print("Correct Answers:",correct,"/ Incorrect Answers:",incorrect)  

main()

您已经很好地使用了 in 语法。如果您只想检查答案是 A、B、C 还是 D,则以下代码可行。

if not answer in ['A', 'B', 'C', 'D']:
    print("Invalid answer.")

此脚本可以进一步受益于 Python 的语法,例如:

if answer not in 'ABCD':
    print("Invalid answer.")
import re

if re.match("^[ABCDabcd]$", answer) is not None:
    # Matched!
else:
    # Didn't match!