[Tutor] User validation was: Re: Converting a txt file to dictionary

Peter Otten __peter__ at web.de
Sat Aug 29 04:30:36 EDT 2020


Alan Gauld via Tutor wrote:

> Please don;t start a new discussion in another thread. start a new
> discussion with a fresh message with a new subject line. That way
> searches in the archives make more sense.
> 
> 
> On 29/08/2020 07:30, nzbz xx wrote:
>> I'm trying to create a def function code to validate user input. I would
>> want the user to only input either 1 or 2. Any other inputs would
>> reprompt the user again. This is what i have so far:
>> 
>>  def data_validation(User_Decision):
>>     try:
>>         if User_Decision != 1 or User_Decision != 2:
>>             print("Please enter option number: 1 or 2.")
>>     except ValueError:
>>         print("Input is invalid. Please try again.")
> 
> This will work although I doubt the try/except will catch any value
> errors since you don;t do anything that would cause one.
> 
> Also your test would be easier using an 'in test:
> 
> if User_Decision not in [1,2]:
>    print(....)
> 
> That is much easier to extend if new values need to be
> included in the future.
> 
>> User_Decision = int(input(">"))
>> 
>> while data_validation(User_Decision):
>>     User_Decision = input(">")
> 
> But here you are testing the return value of your function.
> But you do not return anything from your function you only
> print stuff. Python will supply a default value of None in
> that case which the while loop sees as False and so
> never executes.
> 
> I would suggest  converting your function to simply test the
> value and return True or false, Then in the while loop add
> the error message. Also its often clearer to name predicate
> functions(those with a boolean result) as a statement of
> intent:
> 
> 
> def data_valid(user_decision):
>     return user_decision in [1,2]
> 
> choice = int(input('> '))
> while not data_valid(choice):
>     print("You must enter 1 or 2")
>     choice = int(input('> '))
> 
> Or more Pythonically:
> 
> while True:
>     choice = int(input('> '))
>     if data_valid(choice):
>        break
>     print(" You must enter 1 or 2")
> 
> Which avoids entering the input line twice.
 
In this case it might be ok to use the "walrus" operator:

while not data_valid(choice:=int(input('> '))):
    print("You must enter 1 or 2")
print(choice)

However, for all but the tiniest scripts I would not want that they raise a 
ValueError on wrong user input. To cover both cases, an illegal number and 
not a number at all, you need something a little more complex:

def one_or_two():
    while True:
        try:
            result = int(input("> "))
        except ValueError:
            pass
        else:
            if result in {1, 2}:
                return result
        print("You must enter 1 or 2")
            
print(one_or_two())




More information about the Tutor mailing list