[Tutor] User validation was: Re: Converting a txt file to dictionary
Alan Gauld
alan.gauld at yahoo.co.uk
Sat Aug 29 04:04:01 EDT 2020
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.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list