繁体   English   中英

我想在 python 中的一个变量上使用 2 种数据类型?

[英]I'm trying to use 2 data types on one variable in python?

我试图在我的代码中获取浮点数据类型。 到目前为止,我的代码是;

age = int (input("Age of the dog: "))

if age <= 0:
    print ("This can not be true!")
elif age == 1:
    print ("He/she is about 14 in human years.")
elif age == 2:
    print ("He/she is about 22 in human years.")
elif age > 2:
    human = 22 + (age - 2) * 5
    print ("He/she is about", human, "human years")

由于您没有提到您希望给出的年龄是浮点数还是输出应该是浮点数,我在这里添加了两者:-)

对于仅“获取”浮点数,您的代码就足够了。 除了浮点数将被四舍五入。 如果您不想对数字进行四舍五入,请使用float(input( ,而不是int(input( ,您就可以开始了。

如果您想将年龄处理为浮点数,您可以稍微更改年龄计算逻辑,以确保将年龄处理为浮点数时更具可读性。 添加异常处理也不会受到伤害。

也有异常处理的代码:

try:
    age = float(input("Age of the dog: "))
except:
    print "Age given is not a valid number"
    age = 0

if age <= 0:
    print ("This can not be true!")
elif age == 1:
    human_age = 14
elif age == 2:
    human_age = 22
elif age > 2:
    human_age = 22.0 + ((age - 2) * 5.0)
print ("He/she is about %f human years" % (human_age))

如果您将第一行更改为

age = float(input("Age of the dog: "))

您的程序将显示浮点年龄。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM