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
所以,这是一个简单的小测验的代码,如果我不包含有效/无效的输入部分,它就可以工作。所以我想要完成的是如果用户输入不是“a”“b”“c”或“d”那么它将返回“请使用有效输入”并循环直到有效使用输入。我认为问题可能与我定义“validinput”的方式有关。无论出于何种原因,“a”是唯一可接受的输入,而所有其他输入使用“请使用有效输入”返回程序。无论如何,如果有人知道如何解决这个问题或者完全不同的想法,那将非常感激。谢谢!
答案 0 :(得分:1)
您可以将validinput
更改为列表,然后测试该值是否为not in
validinput。对于这种检查,使用生成器似乎过于复杂。
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
...