How to take float input in Python

Previous
Next

In this tutorial, we will see how to take float input in Python

There is difference in how you can take input in python 2.x and 3.x. You have to use raw_input in python 2.x and input in Python 3.x

In Python 3.x, raw_input was renamed to input and the Python 2.x input was removed.

💡 Did you know?

raw_input always returns a String object and same is the case with input in Python 3.x

Let’s see with the help of example.

Output:

Enter a float:23.43
value of x: 23.43
type of x:

if you want to take float as input, then you need to use float() function to explicitly convert String to float.


Python 3.x example

x = float(input(“Enter a float: “))
y = float(input(“Enter a float: “))

Let’s understand with the help of example.

x = float(input("Enter an float: ")) y = float(input("Enter an float: ")) print("Sum of x and y:",x + y) print("Multiplication of x and y:",x * y)

Output:

Enter an float: 23.43
Enter an float: 34.32
Sum of x and y: 57.75
Multiplication of x and y: 804.1176

Python 2.x example

p = float(raw_input(“Enter a float: “))
q = float(raw_input(“Enter a float: “))

Let’s understand with the help of example.

p = float(raw_input("Enter an float: ")) q = float(raw_input("Enter an float: ")) print("Sum of p and q:",p + q) print("Multiplication of p and q:",p * q)

Output:

Enter an float: 10.34
Enter an float: 20.21
Sum of p and q: 30.55
Multiplication of p and q: 208.97140000000002

If user does not provide float input, then it will raise ValueError: could not convert string to float.
Let’s see with the help of example:

Enter an float: 23.41
Enter an float: NA
Traceback (most recent call last):
File “main.py”, line 2, in
q = float(input(“Enter an float: “))
ValueError: could not convert string to float: ‘NA’

That’s all about How to take float input in Python.

Previous
Next

Add Comment