[英]I'm trying to use 2 data types on one variable in python?
Im trying to get float data type available on my code.我试图在我的代码中获取浮点数据类型。 My code so far is;
到目前为止,我的代码是;
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")
Since you didn't mention whether you want the age given is float or the output should be in float, I added both here :-)由于您没有提到您希望给出的年龄是浮点数还是输出应该是浮点数,我在这里添加了两者:-)
For only "getting" floating point, your code will suffice.对于仅“获取”浮点数,您的代码就足够了。 Except that the floating point number would be rounded off.
除了浮点数将被四舍五入。 If you do not want the number to be rounded, instead of
int(input(
, use float(input(
and you are good to go.如果您不想对数字进行四舍五入,请使用
float(input(
,而不是int(input(
,您就可以开始了。
In case you want to process the age as floating point, you can just change the age calculation logic a little to ensure more readability that you are processing age as float.如果您想将年龄处理为浮点数,您可以稍微更改年龄计算逻辑,以确保将年龄处理为浮点数时更具可读性。 Also adding exception handling won't hurt either.
添加异常处理也不会受到伤害。
The code with exception handling as well:也有异常处理的代码:
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))
If you change your first line to如果您将第一行更改为
age = float(input("Age of the dog: "))
your program will show a floating point age.您的程序将显示浮点年龄。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.