Python float() Function

The python float() function returns a floating-point number from a number or string. A floating-point number, or float, is a mathematical value that contains a decimal point. Floats can be positive or negative and can address both whole numbers and fractional values. In Python, the float() function is utilised to switch a value completely to a float.

Syntax:

Parameters

value- It can be a number or string that converts into a floating point number.

Return

It returns a floating point number.

Python float() Function Example 1

The below example shows the working of float():

Code

Output:

2.0
5.90
-24.17
-17.15
ValueError: could not convert string to float: ' xyz '

Explanation: In the above example, we have given different types of inputs, like an integer, a float value, and a string value. When the argument is passed to the float() function, the output is returned in the form of a floating value.

Note: The important point to note is that the float() method converts only integers and strings into floating-point values. All the other arguments, like list, tuple, dictionary, and None values, result in TypeErrors.

Python float() Function Example 2

Code

Output:

TypeError: float() argument must be a string or a number, not ' list '
TypeError: float() argument must be a string or a number, not ' tuple '
TypeError: float() argument must be a string or a number, not ' dict '
TypeError: float() argument must be a string or a number, not ' NoneType '

Conclusion:

To conclude, the float() function in Python is utilised to change a number or a string that addresses a number to a floating-point value. When utilised accurately, the function can assist you with changing information between various mathematical configurations and performing number-crunching tasks that require floating-point accuracy.






Latest Courses