python 中的用户输入验证
我已经玩了几个小时了,并且尝试了一些变体,但仍然一无所获,不确定我出了什么问题。我正在尝试将其做到,以便用户只能给出A,B或C的输入值。如果有人建议这样做,这将不胜感激。谢谢。
def run_quiz(questions):
"""
Function loops through questions and checks answer given
against correct answer. If correct answer given
then score increases by 1.
"""
score = 0
for question in questions:
answer = input(question.prompt)
answer = answer.lower()
if answer == question.answer:
score += 1
while answer not in {'a', 'b', 'c'}:
return "Invalid answer, try again"
else:
return f"You guessed {answer}"
print(f"{name} got {score} out of {str(len(questions))} questions correct")
I've been playing about with this for a few hours now and have tried a few variations and am still getting nowhere and am not sure what I'm getting wrong. I'm trying to make it so users can only give input values of a, b or c. If anyone could advise that would be greatly appreciated. Thanks.
def run_quiz(questions):
"""
Function loops through questions and checks answer given
against correct answer. If correct answer given
then score increases by 1.
"""
score = 0
for question in questions:
answer = input(question.prompt)
answer = answer.lower()
if answer == question.answer:
score += 1
while answer not in {'a', 'b', 'c'}:
return "Invalid answer, try again"
else:
return f"You guessed {answer}"
print(f"{name} got {score} out of {str(len(questions))} questions correct")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不需要这些
return
语句。There's no need for those
return
statements.