Javaexercise.com

How to take float input in Python?

There is no direct method to take float type user input in python but we use the float() method of python to convert the user input into the float type. In Python, float() is a method that is used to convert user input into float type. For more details read Python Float() method.

Python provides an input() method from Python 3 version to take a user input that returns user input as a string type. Let's have some code examples here.

Take float user input in Python

In this example, the input() method is used to take user input, and the type() method returns the type of user input later we used the float() method to convert this user input to float type. See the code example and output.

# Take user input
val = input("Enter a value: ")
print(val)
print(type(val))
# Cast it to float
float_val = float(val)
print(float_val)
# Check input type
print(type(float_val))

Output:

Enter a value:  12
12
<class 'str'>
12.0
<class 'float'>

 

Take float input in Python: Convert String to Float

While converting the user input make sure you use proper valid input otherwise the float() method will raise an error. Let's see a code example.

# Take user input
val = input("Enter a value: ")
print(val)
print(type(val))
# Cast inputt to float
float_val = float(val)
print(float_val)
# Check input type
print(type(float_val))

Output:

Enter a value:  abc
abc

ValueError: could not convert string to float: 'abc'