Python float() Function

In this we’ll go through the Python float Function, learning how to use to produce float values.

float() is a built-in Python function that converts a number or string to a float value and returns the result. If, due to invalid input this conversion fails, the Exception for ValueError or TypeError is thrown by the Python interpreter.

A possible scenario for a ValueError being thrown is passing a string without numbers into the function.

>>> float('Hello')
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    float('Hello')
ValueError: could not convert string to float: 'Hello'

A possible scenario for a TypeError being thrown is passing an unsupported datatype into it’s parameters. (Such as the None data type)

>>> float(None)
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    float(None)
TypeError: float() argument must be a string or a number, not 'NoneType'

Examples

float() on strings

Make sure the string contains only numbers.

>>> float('4')
4.0
>>> float('356')
356.0
>>> float('5.678')
5.678
>>> float('a5')
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    float('a5')
ValueError: could not convert string to float: 'a5'

float() on Integers

>>> float(5)
5.0
>>> float(-5)
-5.0
>>> float(567)
567.0

float() on float

>>> float(5.6)
5.6
>>> float(6.789)
6.789

This concludes our Article on the float() function. Any suggestions or contributions for CodersLegacy are more than welcome. Questions can be asked in the comment section below.

Here’s a link back to the main Python Built-in Functions page.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments