Home > database >  Allow user to retry input for a function in Python
Allow user to retry input for a function in Python

Time:05-28

My code is a quiz - along the lines of which character in 'The book' are you most like - basically a series of questions with options of a,b,c,d,e as the answers.

`#Question 1
print("This is the text of question 1")
print("a - This is the text of answer a")
print("b - This is the text of answer b")
print("c - This is the text of answer c")
print("d - This is the text of answer d")
print("e - This is the text of answer e")

quest_ans()
answers.append(quest_ans.ans)`

The code next calls a function to allow the user input their answer, the function also takes that answer and converts it to a number, which is passed and appened to a list, for summing at the end.

This is the function quest_ans()

def quest_ans():
    ans=0
    answer=input(str.lower("Please Enter a,b,c,d or e: "))
    if answer.lower() == 'a':
        quest_ans.ans =2
    elif answer.lower() == 'b':
        quest_ans.ans=3
    elif answer.lower() == 'c':
        quest_ans.ans=4
    elif answer.lower() == 'd':
        quest_ans.ans=5
    elif answer.lower() == 'e':
        quest_ans.ans=6
    return quest_ans.ans

As long as the user enters the one of the correct answer options - this all works fine, but I want to manage if the user enters something other than a, b, c, d, e by printing a message to alert them and re calling the function to allow them enter a correct answer. I've tried try except blocks and while loops and I can't get the syntax right.
Any help would be appreciated. Abbie

CodePudding user response:

Use a while loop and loop until a valid condition, which uses break to exit out of the loop. Also, don't need to set a property on the function like quest_ans.ans - note that ans is sufficient by itself.

def quest_ans():
    ans=0
    while True:
        answer=input(str.lower("Please Enter a,b,c,d or e: "))
        if answer.lower() == 'a':
            ans =2
            break
        elif answer.lower() == 'b':
            ans=3
            break
        elif answer.lower() == 'c':
            ans=4
            break
        elif answer.lower() == 'd':
            ans=5
            break
        elif answer.lower() == 'e':
            ans=6
            break
        else:
            print('Try again, bro..')

    return ans

ans = quest_ans()
print('Dude youy entered:', ans)

Note that, technically your code could be improved or simplified through use of a dict mapping answer to numeric value:

ans_map = {'a': 2, 'b': 3, 'c': 4, 'd': 5, 'e': 6}


def quest_ans():

    while True:
        answer = input("Please Enter a,b,c,d or e: ".lower()).lower()

        if answer in ans_map:
            return ans_map[answer]

        print('Try again, bro..')


ans = quest_ans()
print('Dude youy entered:', ans)

CodePudding user response:

Try this:

def quest_ans():
    quest_ans.ans= 0 #just “ans” isn’t actually used
    while True: #to try over and over until a valid response is given
        
        answer=input("Please Enter a,b,c,d or e: ").lower()
        try: #if a 2  character response is given, this will stop ord() causing an error
            if ord(answer) > 96 and ord(answer) < 102: #comparing ASCII of letter
                break
            else:
                print("please try again")
        except:
            print("please try again")

    if answer.lower() == 'a':
        quest_ans.ans =2
    elif answer.lower() == 'b':
        quest_ans.ans=3
    elif answer.lower() == 'c':
        quest_ans.ans=4
    elif answer.lower() == 'd':
        quest_ans.ans=5
    elif answer.lower() == 'e':
        quest_ans.ans=6
    return quest_ans.ans
  • Related