How to take Float user input in Python
Collecting float values from user input is a common task in interactive Python applications.
This guide explores different methods for obtaining float input, including input validation, error handling, and range checking. You'll learn how to ensure your programs receive valid float values.
Basic Float Input with float()
The most straightforward approach to take float input is by using the input()
function to get the input from the user, and then immediately converting that input to a float using the float()
constructor.
user_input = float(input('Enter a float: '))
print(user_input)
The input()
function always returns a string. The float()
constructor then attempts to convert the returned string into a float.
Handling ValueError
Exceptions
If the user enters a non-numeric string that can not be converted to a float, the float()
constructor raises a ValueError
. Use a try
/except
block to handle this situation:
try:
user_input = float(input('Enter a float: '))
print(user_input)
except ValueError:
print('Enter a valid float')
- The
try
block contains the code which can potentially throw an exception. - The
except ValueError
block handles theValueError
exception that is raised if the input can not be converted to a float.
Validating Input with a Loop
To ensure that the user only enters valid float input, embed the try
/except
block in a while
loop:
while True:
try:
num = float(input("Enter your favorite float: "))
except ValueError:
print("Please enter a valid float")
continue
else:
print(f'You entered: {num}')
break
Explanation:
- A
while True
loop will continue prompting for input. - If a
ValueError
is raised in thetry
block, an error message is displayed and the loop continues with thecontinue
statement. - If a valid float is entered, the
else
block runs and the program displays a confirmation message and uses thebreak
statement to exit the loop.
Limiting Input to a Specific Range
You can add range checking using an if
statement inside the else
block. This way you can force the user to only enter a float within a specific range.
while True:
try:
num = float(input("Enter a float 1.1-9.9: "))
except ValueError:
print("Please enter a valid float 1.1-9.9")
continue
if 1.1 <= num <= 9.9:
print(f'You entered: {num}')
break
else:
print('The float must be in the range 1.1-9.9')
Explanation:
- The
try
/except
block remains the same. - An
if
statement checks whether the input is within the specified range using boolean operators (>=
and<=
). If it is in range the program will display a confirmation message and exit the loop. - If the number is not within the specified range, the else block displays an error and prompts the user for input again.