Float built-in function in Python

float() is a part of the built-in function of the Python Interpreter.

class float(x=0.0)

The float() function returns a floating point number from the passed in number or string x.

Example 1: passing a String argument

>>> float('10.5')
>>> float('-10.5')
>>> float('10')
>>> float('-10')
>>> float('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'a'

Documentation: https://docs.python.org/3/library/functions.html#float

passing a String argument to float function

Example 2: passing exponential values:

>>> float('2e3')
>>> float('-2e3')
Example 3: When no argument is passed

When no argument is passed, the value is set as 0.0

>>> float()

Example 4: NaN and infinity

>>> float('NaN')
>>> float('Infinity')
>>> float('-Infinity')

Python 3 Code example with float()

Add two float numbers

float1 = float(input("Enter float number 1: "))
float2 = float(input("Enter floart number 2: "))

sum_of_two_numbers = float1 + float2

print(f"Sum of {float1} and {float2} is {sum_of_two_numbers}")

Enter float number 1: 1.4
Enter float number 2: 2.4
Sum of 1.4 and 2.4 is 3.8


Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap