首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Python中重新启动"for“循环

如何在Python中重新启动"for“循环
EN

Stack Overflow用户
提问于 2022-05-09 06:38:43
回答 2查看 89关注 0票数 1

我有一个关于python编码的问题

如果我的行话过时或难以理解的话,我对自己的道歉是很陌生的。

我正在努力学习如何创建一个多个问题测试,其中用户只能输入一个字符串作为for循环中的输入,如果他们输入任何其他数据类型,它将重新启动for循环(再次问问题)。

这是我有的东西

代码语言:javascript
复制
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)

谢谢您的帮助:)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-05-09 07:03:01

我想我知道你想做什么,但是你的要求定义得很差。input()函数总是返回一个字符串,正如您在文档中看到的那样。因此,您不能真正将您的需求定义为需要“一些字符串”作为输入。即使用户输入您认为是int (如3 )的内容,输入函数也会为您提供str "3"。因此,您需要一些额外的需求,然后检查用户输入的内容是否是您认为的“有效”字符串。假设您想出了一些函数来验证您的字符串以满足您的需求,我将继续执行其余的答案

代码语言:javascript
复制
def is_valid(string: str) -> bool:
    """checks if the string is valid"""
    # validation code goes here

考虑到您的问题是一个选择题,假设您希望用户输入与答案相对应的选项,那么您的验证代码可能是

代码语言:javascript
复制
def is_valid(string: str) -> bool:
    valid_options = ['a', 'b', 'c', 'd']
    return string.lower() in valid_options

现在,要一直循环直到用户输入有效的输入,您可以执行以下操作

代码语言:javascript
复制
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)
票数 1
EN

Stack Overflow用户

发布于 2022-05-09 06:46:14

您需要使用isinstance(变量,str)返回布尔值。

代码语言:javascript
复制
if isinstance(question, str) != True:
        print("Wrong input option please enter a letter")
票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72167832

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档