簡體   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