Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Confirmation function in python

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.

like image 832
luishengjie Avatar asked Sep 15 '26 00:09

luishengjie


1 Answers

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.")
like image 174
tzaman Avatar answered Sep 16 '26 14:09

tzaman