Python:验证用户的输入?

时间:2015-04-14 16:57:48

标签: python list input

我的变量userAnswerList[]接受用户的输入,我需要验证用户是否输入ABCD以外的输入

以下是我的代码,并想知道如何在(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()

2 个答案:

答案 0 :(得分:3)

您已经在使用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.")

答案 1 :(得分:-1)

import re

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