Python float()
时间:2020-02-23 14:42:42 来源:igfitidea点击:
在本教程中,我们将学习python float()函数。
在上一教程中,我们了解了Python Join。
Python float()
顾名思义,pythonfloat()
函数返回一个浮点数。
它采用一个参数,并且是可选的。
因此,python float()函数的基本语法为;
其中项目可以是字符串,整数或者浮点数。
因此,以下代码给出了有关python float的基本示例。
# 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)
因此,如果您检查输出,您会发现
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()特殊参数
如前所述,float()函数的参数是可选的。
因此,如果您打印一个空白的float()函数,它将打印什么?
好吧,它将输出0.0作为输出。
同样,您可以使用此函数在float中定义无穷大值,还可以定义NaN(非数字)。
为此,您只需要放入一个包含inf
或者NaN
作为参数的字符串。
下面的代码将指导您有关此的操作。
# 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)
这样您将获得输出。
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