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

标签 python python-3.x

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/

相关文章:

python - x = None 或 object() 是否等于显式检查?

python - Python 高手如何识别和检查 Python 3 数据结构的内容?

python-3.x - FastAPI 使用 POST 请求将文件下载到客户端

python - 针对 1 个重复键访问多个值

python - 如何使用 MongoKit 对远程数据库主机进行身份验证?

python - 我需要发送不止一个 socket.send() 到一个 http 请求

python-3.x - python/sqlachemy/ibmdb2 - sqlAlchemy 插入 Db2 for i,AS400?

python - 如何从提取的帧中制作视频?

python - Bokeh 悬停工具提示可显示来自不同列的数据

Python 在 "import"上找不到模块(最小项目,无外部导入)