3
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.

luishengjie
  • 187
  • 6
  • 15
  • 3
    Possible duplicate of [How do I use try .. except or if ...else to validate user input?](http://stackoverflow.com/questions/5557937/how-do-i-use-try-except-or-if-else-to-validate-user-input) – jeremycg Apr 14 '16 at 17:44

2 Answers2

7

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.")
tzaman
  • 46,925
  • 11
  • 90
  • 115
  • Is there a way to do this without having to press `Enter` (i.e., just `c` or `v`)? – AstroFloyd Nov 13 '22 at 10:01
  • 1
    @AstroFloyd See [this question](https://stackoverflow.com/questions/510357/how-to-read-a-single-character-from-the-user) for ways to read single characters. – tzaman Nov 14 '22 at 14:55
  • Thanks, that led me to the getch package on PyPI: https://pypi.org/project/getch/, which basically allows me to replace `input()` with `getch()` or `getche()`. – AstroFloyd Nov 15 '22 at 16:33
4

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.

Ilja Everilä
  • 50,538
  • 7
  • 126
  • 127