Python if User Doesnt Enter Int Try Again

Input returns a string, but you don't want that, do you lot?

Image past X posid on Public Domain Pictures

Ane question I run into a lot in various Facebook groups and on Stack Overflow is about user input and how to handle that input.

In Python, you tin ask for user input with the function input():

user_input = input('Type your input hither: ')

input() returns a cord containing what the user typed into the terminal with their keyboard.

Sometimes yous're looking for a different type, though. Maybe you want information technology to be an integer you'll apply in a calculation or as an alphabetize for something.

What will fail in the following code?

          food_list = ['milk' , 'staff of life' , 'cheese']
print (f'Item Choices:')
for index, item in enumerate(food_list):
print(f'{alphabetize} : {detail}')
user_input = input('choose an detail: ')
impress (f'user chose {food_list[user_input]}')

You probably guessed it already. Yous tin't use a string as an index to fetch the value stored in that list position. Even if the user types "one," information technology'll neglect considering the input is withal stored as a string.

          Traceback (most contempo call last):
File "main.py", line half-dozen, in <module>
print (f'user chose {food_list[user_input]}')
TypeError: listing indices must be integers or slices, not str

"Just int() that input(), bro. They'll get a user error if they type something incorrect."

Actually, no. A lot of developers have this mindset. If a user is able to break the system by doing something wrong, we have to expect at the system.

Even though this would brand the code run …

          user_input = int(input('cull an item: '))        

… it'd crash if the user typed "«ane»" or "1.0" — or any other gibberish. In this instance, it might look absurd, merely in more than circuitous lawmaking, it could have a greater impact. One of my supervisors lived by this quote when we developed our pipeline:

"Presume human intelligence ."

— Espen Nordahl, CG supervisor at Storm Studios

The quote e'er makes me giggle, and it makes sense. But in the last few years, I've been more than open to admitting the system should support the user more, and nosotros demand to blueprint to prevent errors from happening.

Pitiful for going all UX hither, back to the code:

If y'all write a part that calculates the area of a rectangle — but information technology merely accepts integers — I think a lot of users would break the programme by typing in a floating indicate (e.yard., 32.4) instead. Float would make a lot of sense in this example to the user.

How tin you brand sure you get what you lot ask for?

In this piece, we'll first create all the functions to check the type, and then we'll make an interaction carte du jour where we put them to the test.

Coding Time

Photo by Priscilla Du Preez on Unsplash

Permit'due south break it downwardly into what we wish to check for:

  • integer
  • string
  • float

The type string in Python already has a lot of built-in functions that give us the results we want for free. Yay, Python.

We want to support and check for these:

  1. HelloWorld (all letters, nothing more than, nil less)
  2. Hello Earth (pay attending to the space)
  3. HelloWorld123 (both letters and/or numbers)
  4. 123 (pure number, int)
  5. 12.2 (floating indicate)

1. Cheque if the variable is all letters (alpha):

This means all characters in the cord are letters. Not even a space is allowed here.

          def is_string_only(check_input):
if check_input.isalpha():
render True
return Fake

As yous tin see, this is actually just using the Python built-in function. Our main lawmaking could have used this directly out of the box if nosotros wanted information technology. Writing it into our own function is more for learning purposes.

          user_input = input('')
if user_input.isalpha():
#do incredible things

Note that yous don't need to say:

          if something:
return True
else:
return Fake

If the if statement evaluates to True, the function volition return True and then finish. Therefore, we'll never get to the last line proverb return Simulated.

If the if statement doesn't evaluate to True, it just keeps going downward every line and ends up at return False. In that location'southward no need for else.

Interaction with the office would await similar this:

Terminal Window testing two strings to check if they are all alpha characters.

"HelloWorld" is valid considering all characters are letters. "Hi Globe" has a space and isn't valid.

2. Bank check if the variable is all letters and contain any spaces

As yous could run across to a higher place, if there are any spaces in the string, information technology'll neglect because space isn't an alpha.

The string has a office called isspace(). I'g using it to check if there are any spaces in the cord and at the same time if the rest are letters.

          def is_string_with_space(check_input):
valid = Fake
if ' ' in check_input:
for char in check_input:
if char.isdigit():
valid = Fake
elif char.isalpha() or char.isspace():
valid = True
return valid

First, I check if there are any spaces in our passed string. A temp variable, valid, is used so we won't break out of the loop the first fourth dimension we discover a Truthful or Imitation argument. Recollect, the function considers the piece of work washed when it returns something.

If there's a space, I loop through all the characters and return Imitation if I tin can observe any digits. This is optional. If you lot desire to support numbers, you tin leave it. In the end, I cheque if the items in the variable are either a letter or infinite. And so I return valid.

A role like this could be used to check if users enter a valid proper name.

Interaction with the function would await similar this:

Terminal testing different strings with spaces.

Only the middle one with messages and a space between is valid

3. Check for both letters and/or numbers

I tin't think of many settings you lot'd use this on, just maybe you'd need it for a username or something. It's identical to the .alpha() function:

          def is_string_or_num(check_input):
if check_input.isalnum():
return Truthful
return False

If yous want to force it to exist both numbers and letters, you can loop through the elements in the string every bit we did in the previous check.

This function doesn't support spaces. That would be another thing you could incorporate equally well if yous like.

Interaction with the function would look like this:

Terminal interaction where user types in user name containing letters and/or numbers

User typing in username containing letters and/or numbers

iv. Check for Integers

This is some other easy one. The function to cheque for int can be:

          def is_digit(check_input):
if check_input.isdigit():
return True
return False

This checks if all the characters in the string are digits. Note that this one doesn't support spaces either.

Interaction with the function would look similar this:

Terminal showing how we check for integers.

Only integers are valid inputs

4. Bank check for a floating indicate

This was as well a really funny i. If yous know a amend way to cheque for float (other than effort/except), delight let me know.

          def is_float(check_input):
if '.' in check_input:
split_number = check_input.split('.')
if len(split_number) == two and split_number[0].isdigit() and split_number[ane].isdigit():
return Truthful
return False

The first thing I do is check if there's a dot in hither. If there'southward no dot, it can't be a float.

Nosotros can't only say it'southward a float if there's a dot there, though. What if the user writes a sentence?

Therefore, I did a split on the dot split('.') . By checking the length of this one, I can effigy out if information technology's a potential float. It has to be two: numbers in front of the dot and numbers after the dot.

To brand sure it actually is a number, I check if both indexes of the list created after the split up is a digit using .isdigit().

Clever? Clunky? I don't know. Super fun at least.

Interaction with the function would look like this:

Terminal showing interaction checking for floating point numbers

Checking for decimal numbers.

When you're washed with all the functions, it should feel similar this:

Photo past MI PHAM on Unsplash

Final Fun: Use the Functions for Something Useful

Nutrient list

If we get back to the food list, we tin create a menu once more.

This time, nosotros modify it with checkups to make sure the program runs even if the user types in inputs we aren't looking for. I'd normally have the functions in a separate file and maybe fifty-fifty make a class for this, but for this example, I'll go on all the lawmaking in 1 Python file.

If you accept read my article on adding information to a CSV file, you're already familiar with how I create user menus that keep going until the user inputs something predefined to go out.

Below is code we could use for the list example we had earlier.

For this little program, nosotros want the user to type an int. That'south the only valid input we can take to access the items within the list. Since we're absolutely sure the user typed an int, we tin utilize int(input()).

If the user types in an invalid input, they'll get another chance until they get it right. I've likewise added an pick for the user to exit the program typing past typing "q." I chose "exit" earlier, but "q" is shorter for the user.

Terminal showing interaction with food list menu

User interacting with our menu

In Decision

Making sure the user really typed in the correct type makes cleaner lawmaking and dramatically lowers the run a risk of fault.

If an error occurs, the programme throws the user out into the empty void. You lot really don't want the user to burn upward the programme once more just because they entered an wrong value.

At present, you lot can make sure the user stays until the job is done — which is what software is about in the first identify.

Savour writing amend code, and let me know if you accept better ways of handling input. I'm sure there are more ways to solve this.

davisheizieray.blogspot.com

Source: https://betterprogramming.pub/how-you-make-sure-input-is-the-type-you-want-it-to-be-in-python-521f3565a66d

0 Response to "Python if User Doesnt Enter Int Try Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel