Check if user input is a Float in Python

avatar

Borislav Hadzhiev

Last updated: Aug 22, 2022

banner

Photo from Unsplash

Check if user input is a Float in Python #

Use a try/except statement to check if a user input is a float. If the input value is a floating-point number, the try block completes running, otherwise a ValueError is raised which can be handled in the except block.

main.py
# ✅ Check if user input is a float (try/except) float_input = input('Enter a floating-point number: ') try: float_input = float(float_input) print(float_input) except ValueError: print('The provided value is not a float') # ----------------------------------------- # ✅ Keep prompting the user until they enter a float (while loop) float_input = 0 while True: try: float_input = float(input("Enter a floating-point number: ")) except ValueError: print("Please enter a valid floating-point number") continue else: print(f'You entered: {float_input}') break

The first example uses a try/except statement to check if the input value is a valid float.

If we pass a value that is not a valid float to the float() class, a ValueError is raised.

main.py
float_input = input('Enter a floating-point number: ') try: float_input = float(float_input) print(float_input) except ValueError: print('The provided value is not a float')

check if input is float

If the user entered a floating-point number, the try block completes and the except block doesn't run.

If the provided value is not a float, the except block runs.

You can use a while loop if you need to keep prompting the user until they enter a valid float.

Keep asking for user input until a Float is entered #

The following example uses a while True loop to keep iterating until the user enters a valid floating-point number.

main.py
float_input = 0 while True: try: float_input = float(input("Enter a floating-point number: ")) except ValueError: print("Please enter a valid floating-point number") continue else: print(f'You entered: {float_input}') break

keep asking for input until valid float

If the code in the try block raises a ValueError, the except block runs, where we use the continue statement to continue to the next iteration.

If the user enters a valid float, the try block completes successfully and then the else block runs where we use the break statement to exit out of the while loop.

The continue statement continues with the next iteration of the loop.

The break statement breaks out of the innermost enclosing for or while loop.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.