Home > Mobile >  How to restart a "for" loop in Python
How to restart a "for" loop in Python

Time:05-09

I have a question for python coding

I am very new to coding my apologies if my lingo is off or hard to understand

I am trying to learn how to create a multiple question test where the user can only input a string as the input in the for loop, and if they put any other datatype it restarts the for loop ( asks the question again)

Here is what I have

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)

Thank you in advance for the help :)

CodePudding user response:

I think I know what you're trying to do, but your requirement is rather poorly defined. The input() function always returns a string as you can see in the documentation. So you can't really define your requirement as requiring "some string" as the input. Even if the user inputs what you consider an int like 3, the input function gives you the str "3". So you'll need some kind of additional requirements and then check to see if what the user inputed is what you consider a "valid" string. I'll proceed with the rest of the answer assuming you come up with some function that'll validate your string for your requirements

def is_valid(string: str) -> bool:
    """checks if the string is valid"""
    # validation code goes here

Considering your question is a multiple choice question and assuming you want the user to input the option corresponding to the answer perhaps your validation code could possibly be

def is_valid(input: str) -> bool:
    valid_options = ['a', 'b', 'c', 'd']
    return input.lower() in valid_options

now to keep looping until the user inputs a valid input you can do something like

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)

CodePudding user response:

You need to use isinstance(variable, str) returns boolean value.

if isinstance(question, str) != True:
        print("Wrong input option please enter a letter")
  • Related