-1

I'm trying to learn how to do user input validation and build off this post How to return a specific point after an error in 'while' loop

I believe the issue is when current_answer is evaluated against the answer list. Regardless of what I enter for a number, the 'else' statement kicks in.

def input_validator(question, answers):
    while True:
        current_answer = input(question)
        if current_answer in answers:
            print('Success')
            break
        print ('Failure')
    return current_answer

inputQuarter = input_validator('What quarter is being processed (1,2,3,4)?: ', [1,2,3,4] )

I'm assuming the problem lies with something I don't understand about breaking the for loop because the if/else statement seems to work fine outside of the loop.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
CMH89
  • 107
  • 1
  • 10

1 Answers1

1

When you call the function here:

inputQuarter = input_validator('What quarter is being processed (1,2,3,4)?: ', [1,2,3,4] )

Then the answers going to hold a list with the values: [1,2,3,4], that is 4 integers. When you call the function input() like this:

current_answer = input(question)

No matter what is the input the user gave you, it will never be evaluated to True here:

if current_answer in answers:

Because answers hold list of integers and input() returns a string. Therefore current_answer is a string.

You can solve this in 2 ways:

  1. Make the list as list of strings:
inputQuarter = input_validator('What quarter is being processed (1,2,3,4)?: ', ["1","2","3","4"] )
  1. Make the current_answer to an integer:
current_answer = int(input(question))

I personally prefer the first, because it will work for more complicated answers as well (Just know that it will be case sensitive!).

Eladtopaz
  • 1,036
  • 1
  • 6
  • 21