简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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