[英]How to check Datatype with if else in Python?
我想使用if else
检查 python 中的数据类型
Output 我想要:如果用户输入 float 数据类型所以它打印It is float
或者如果用户输入另一个Datatype
所以它打印it is not float
代码:
c=(input("Enter the value\n"))
if type (c) == float:
print('it is float')
else:
print("it is not float")
Output 我要:
Enter the value
12.1
it is float
Output 我得到:
如果我输入float datatype
,它仍在打印it is else
Enter the value
12.1
it is else
你应该有这样的东西
c = (input("Enter the value\n"))
try:
f = float(c)
is_float = True
except ValueError:
is_float = False
c=input("Enter the value\n")
try:
float(c)
print('it is float')
except ValueError:
print("it is not float")
你的问题是输入总是给你 str 值所以通过尝试将它转换为 float 你知道它是否是 float
检查 object 是整数还是浮点数: isinstance()
可以使用内置的 function type() 获取 object 的类型。
i = 100
f = 1.23
print(type(i))
print(type(f))
# <class 'int'>
# <class 'float'>
内置的 function isinstance(object, type) 可用于确定 object 是否为特定类型。
获取/确定 Python 中 object 的类型: type()
, isinstance()
print(isinstance(i, int))
# True
print(isinstance(i, float))
# False
print(isinstance(f, int))
# False
print(isinstance(f, float))
# True
在这种情况下,由于只检查类型,无法判断float的值是否为integer(小数部分为0)。
f_i = 100.0
print(type(f_i))
# <class 'float'>
print(isinstance(f_i, int))
# False
print(isinstance(f_i, float))
# True
source: check_int_float.py
Check if float is integer: is_integer()
float has is_integer() method that returns True if the value is an integer, and False otherwise.
f = 1.23
print(f.is_integer())
# False
f_i = 100.0
print(f_i.is_integer())
# True
例如,对于 integer 数字(整数或 integer 浮点数)返回 True 的 function 可以定义如下。 这个 function 为 str 返回 False。
def is_integer_num(n):
if isinstance(n, int):
return True
if isinstance(n, float):
return n.is_integer()
return False
print(is_integer_num(100))
# True
print(is_integer_num(1.23))
# False
print(is_integer_num(100.0))
# True
print(is_integer_num('100'))
# False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.