1
print("Mathematics Quiz")
question1 = "What is the square root of 16?"
options1 = "a. 4\nb. 6\nc. 2\nd. 16\n"
options2 = "a. Chang'e\nb. Hou Yi\nc. Jing Wei\nd. Susano\n"
question2= "Who is the Chinese God of the sun?"
print(question1)
print(options1)
validinput = ("a" and "b" and "c" and "d")
# Attempts = 2 per question

while True:
    response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n")
    while response is not validinput:
      print("Please use a valid input")
      break
    else:
      if response == "a":  
        print("Correct! You Got It!")
        break
      elif response == "b" or "c" or "d":
        print("Incorrect!!! Try again.")

        while True:
            response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n")

            if response == validinput:
              print("Correct! You Got It!")
              stop = True
              break
            else:
                print("Incorrect!!! You ran out of your attempts!")
                stop = True
                break
        if stop:
            break

So, This is code for a simple little quiz, and it works if I don't include the valid/invalid input part. So what i'm trying to accomplish is to make it so if the user input is anything other than "a" "b" "c" or "d" then it will return "Please use a valid input" and loop until a valid input is used. I believe the problem may be with the way i defined "validinput". For whatever reason, "a" is the only accepted input while all others make the program return with "Please use a valid input". Anyways it would be much appreciated if anyone knew how to either fix this or had a different idea altogether. Thanks!

Alex
  • 13
  • 3
  • 1
    Possible duplicate of [How do I test one variable against multiple values?](http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values) – vaultah Apr 18 '17 at 21:30

1 Answers1

1

You could change the validinput to be a list, then test if the value is not in validinput. Using a generator seems overly complicated for that kind of check.

valid_input = ['a', 'b', 'c', 'd']

while True:
    response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n")
    if response not in valid_input:
      print("Please use a valid input")
      continue   # re-start the main while loop
...
  • 1
    Yes! Thank you so much! Worked perfectly. But by chance do you know what was wrong with the original code? @Christopher Apple – Alex Apr 18 '17 at 21:49
  • I think it was the fact that you were using booleans with strings inside your generator. Here's some information on what happens when you use `and` with two strings: http://stackoverflow.com/questions/19213535/using-and-and-or-operator-with-python-strings – Christopher Apple Apr 18 '17 at 21:53
  • ok. Thanks for the help! I Think a problem may be that my method of listing is wrong as i'm new to script based programming. @Christopher Apple – Alex Apr 18 '17 at 21:55