Creating a Confirmation function in python

Question:

def confirm_choice():
    confirm = input("[c]Confirm or [v]Void: ")
    if confirm != 'c' and confirm != 'v':
        print("n Invalid Option. Please Enter a Valid Option.")
        confirm_choice() 
    print (confirm)
    return confirm

When an invalid input has been keyed in for example, the letter ‘k’ followed by a valid input ‘c’, the function would print both inputs ‘c’ and ‘k’

Output:

c
k

How can the above program be altered so that it returns only either ‘c’ or ‘v’and repeats the function if the input is invalid.

Asked By: luishengjie

||

Answers:

You forgot to return after recursively calling confirm_choice() and so it falls out of the if-block and executes

print (confirm)
return confirm

which will print the first invalid input.

def confirm_choice():
    confirm = input("[c]Confirm or [v]Void: ")
    if confirm != 'c' and confirm != 'v':
        print("n Invalid Option. Please Enter a Valid Option.")
        return confirm_choice() 
    print (confirm)
    return confirm

should behave correctly.

Answered By: Ilja Everilä

Recursion is unnecessary; it’s easier to use a while loop for this:

while True:
    confirm = input('[c]Confirm or [v]Void: ')
    if confirm.strip().lower() in ('c', 'v'):
        return confirm
    print("n Invalid Option. Please Enter a Valid Option.")
Answered By: tzaman