Table of Contents
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 withinput
in Python 3.x
Let’s see with the help of example.
1 2 3 4 5 |
x=input("Enter a float:") print("value of x: ", x) print("type of x: ", type(x)) |
Output:
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
y = float(input(“Enter a float: “))
Let’s understand with the help of example.
1 2 3 4 5 6 |
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: 34.32
Sum of x and y: 57.75
Multiplication of x and y: 804.1176
Python 2.x example
q = float(raw_input(“Enter a float: “))
Let’s understand with the help of example.
1 2 3 4 5 6 |
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: 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: 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.