In this tutorial we are going to learn about python float() function. In our previous tutorial we learned about Python Join.
Python float()
As the name says, python float()
function returns a floating point number. It takes one parameter and that is optional. So the basic syntax of python float() function is;
Here, item can be string, integer or float. So the basic example about python float is given in the following code.
# init a string with the value of a number
str_to_float="12.60"
# check the type of the variable
print('The type of str_to_float is:', type(str_to_float))
# use the float() function
str_to_float = float(str_to_float)
# now check the type of the variable
print('The type of str_to_float is:', type(str_to_float))
print('n')
# init an integer
int_to_float = 12
# check the type of the variable
print('The type of int_to_float is:', type(int_to_float))
print(int_to_float)
# use the float() function
int_to_float = float(int_to_float)
# now check the type of the variable
print('The type of int_to_float is:', type(int_to_float))
print(int_to_float)
So, if you check the output, you will find
The type of str_to_float is: <class 'str'>
The type of str_to_float is: <class 'float'>
The type of int_to_float is: <class 'int'>
12
The type of int_to_float is: <class 'float'>
12.0
Python float() special parameters
As we said earlier, the parameter of float() function is optional. So if you print a blank float() function, what will it print?
Well, it will print 0.0 as output. Again you can define infinity value in float and also NaN (Not A Number) using this function. To do so, you just have to put a string containing inf
or NaN
as parameter. Here the following code will guide you about this.
# store the valure returned by float()
store = float()
# check the type of the variable
print('The type of variable store is :', type(store))
# print the value stored in the variable
print('The value of store :', store)
print()
# store the infinite value by float()
store = float('inf')
# check the type of the variable
print('The type of variable store is :', type(store))
# print the value stored in the variable
print('The value of store :', store)
print()
# store the 'Not a Number' value by float()
store = float('NaN')
# check the type of the variable
print('The type of variable store is :', type(store))
# print the value stored in the variable
print('The value of store :', store)
And you will get output like this.
The type of variable store is : <class 'float'>
The value of store : 0.0
The type of variable store is : <class 'float'>
The value of store : inf
The type of variable store is : <class 'float'>
The value of store : nan
So, That’s all about Python float function. Hope that you learned well. For any further query, feel free to use the comment box below.