Read Float from Command Line
To read floating-point number from command line in Python, we can use input() builtin function. Since, input() function reads a string from standard input, we can use float() function to convert the string to float.
The following is a simple code snippet to read a float into variable x
.
x = float(input())
We can also prompt user via input() function.
x = float(input('Enter a float : '))
Examples
ADVERTISEMENT
Read floating-point number from user
In the following example, we read a float from user into variable x
, using input() and float() functions.
Python Program
try: n = float(input('Enter a float : ')) print('N =', n) except ValueError: print('You entered an invalid float')
Output
Enter a float : 3.14 N = 3.14
Now, we shall read two floating-point numbers from user, add them, and print the result to output.
Python Program
try: a = float(input('Enter a : ')) b = float(input('Enter b : ')) output = a + b print('Sum :', output) except ValueError: print('You entered an invalid float')
Output
Enter a : 3.14 Enter b : 1.35 Sum : 4.49
Conclusion
In this Python Tutorial, we learned how to read a floating-point number from user, using input() and float() function.