我有一个关于python编码的问题
如果我的行话过时或难以理解的话,我对自己的道歉是很陌生的。
我正在努力学习如何创建一个多个问题测试,其中用户只能输入一个字符串作为for循环中的输入,如果他们输入任何其他数据类型,它将重新启动for循环(再次问问题)。
这是我有的东西
class question:
def __init__(self, prompt, answer):
self.prompt = prompt
self.answer = answer
question_prompt = [
"what is 2+2? \n a 3 \n b 4 \n c 5 \n d 6 \n input answer here ",
"what is 3+3? \n a 4 \n b 5 \n c 6 \n d 7 \n input answer here ",
"what is 10-2?\n a 7 \n b 9 \n c 8 \n d 6 \n input answer here "
]
questions = [
question(question_prompt[0],"b"),
question(question_prompt[1],"c"),
question(question_prompt[2],"c")
]
def run_test(questions):
score = 0
for question in questions:
answer = str(input(question.prompt))
if answer == question.answer:
score += 1
## if xxxxxxx(): ## This is the line I need help with I want to check if the input is a string and if not print("Wrong input option please enter a letter")
print("you got " + str(score) + "/" + str(len(questions)))
run_test (questions)谢谢您的帮助:)
发布于 2022-05-09 07:03:01
我想我知道你想做什么,但是你的要求定义得很差。input()函数总是返回一个字符串,正如您在文档中看到的那样。因此,您不能真正将您的需求定义为需要“一些字符串”作为输入。即使用户输入您认为是int (如3 )的内容,输入函数也会为您提供str "3"。因此,您需要一些额外的需求,然后检查用户输入的内容是否是您认为的“有效”字符串。假设您想出了一些函数来验证您的字符串以满足您的需求,我将继续执行其余的答案
def is_valid(string: str) -> bool:
"""checks if the string is valid"""
# validation code goes here考虑到您的问题是一个选择题,假设您希望用户输入与答案相对应的选项,那么您的验证代码可能是
def is_valid(string: str) -> bool:
valid_options = ['a', 'b', 'c', 'd']
return string.lower() in valid_options现在,要一直循环直到用户输入有效的输入,您可以执行以下操作
for question in questions:
answer = input(question.prompt)
while not is_valid(answer):
print("Wrong input, please enter a valid input")
answer = input(question.prompt)发布于 2022-05-09 06:46:14
您需要使用isinstance(变量,str)返回布尔值。
if isinstance(question, str) != True:
print("Wrong input option please enter a letter")https://stackoverflow.com/questions/72167832
复制相似问题