-3

My variable userAnswerList[] takes the user's input, and I need to verify if the user has input other than A, B, C, D.

Here's my code below, and wondering how should I validate user's input between the range of (A B C D) and if not print the error message?

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()
Falko
  • 17,076
  • 13
  • 60
  • 105
kyle lee
  • 23
  • 8
  • 2
    If your next question is going to be "ok, I figured out how to check if a variable is A B C or D. Now how do I go back and ask the user to try again?", this may be useful to you: [Asking the user for input until they give a valid response](http://stackoverflow.com/q/23294658/953482) – Kevin Apr 14 '15 at 17:04
  • thanks for the link ; I will try "try-except" – kyle lee Apr 14 '15 at 17:06

2 Answers2

3

You are already using the in syntax well. If you only want to check whether the answer is either A, B, C or D the following code would work.

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

This script can further benefit from Python's syntax as such:

if answer not in 'ABCD':
    print("Invalid answer.")
Matt Davidson
  • 728
  • 4
  • 9
-1
import re

if re.match("^[ABCDabcd]$", answer) is not None:
    # Matched!
else:
    # Didn't match!
Falko
  • 17,076
  • 13
  • 60
  • 105
Carson Crane
  • 1,197
  • 8
  • 15
  • regex seems like overkill here. You can solve the problem using only built-in functionality. – Kevin Apr 14 '15 at 17:03