首页 > 解决方案 > 这是正确的格式吗

问题描述

我的目标是找出这是否是正确的格式以找出类类型返回变量的数据类型类

我的预期结果是看到<class 'float'>,但我得到了这个

这是我输入以获得结果<class 'float'>但得到错误的代码print(float(type(a)))

这是我分配给变量的数字a

a*=2
Traceback (most recent call last):
File "C:\Webucator\assignment_operators.py", line 27, in <module>
    print(float(type(a)))

TypeError: float() argument must be a string or a number, not 'type'

标签: python

解决方案


您的功能顺序颠倒了。

type(..)函数返回传递对象的类型,在 Python 中是另一个对象,称为Type Object。打印类型对象会给你类似<class 'int'><class 'float'>取决于对象的东西。

字符串数字float(x)返回浮点数。你不能将类型对象传递给,所以你不能这样做。floatfloat(type(a))

你需要float(a)先在type().

>>> a = 1
>>> a*=2
>>> type(a)
<class 'int'>
>>> float(a)
2.0
>>> type(float(a))
<class 'float'>

推荐阅读