gpt4 book ai didi

python - 尝试添加无效/有效的输入系统

转载 作者:太空宇宙 更新时间:2023-11-03 15:21:43 25 4
gpt4 key购买 nike

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”是唯一接受的输入,而所有其他输入都使程序返回“请使用有效的输入”。无论如何,如果有人知道如何解决这个问题或完全有不同的想法,我将不胜感激。谢谢!

最佳答案

您可以将 validinput 更改为列表,然后测试该值是否不在 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
...

关于python - 尝试添加无效/有效的输入系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43482534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com