import traceback
def calculator():
# Get dog age
age = input("Input dog years: ")
try:
# Cast to float
dage = float(age)
if dage > 0:
if dage <= 1:
print ("The given dog age " + str(dage) + " is " + str(round(dage * 15) ) + " in human years")
elif 1 < dage <= 2:
print ("The given dog age " + str(dage) + " is " + str(round(dage * 12) ) + " in human years")
elif 2 < dage <= 3 :
print ("The given dog age " + str(dage) + " is " + str(round(dage * 9.3) ) + " in human years")
elif 3 < dage <= 4 :
print ("The given dog age " + str(dage) + " is " + str(round(dage * 8) ) + " in human years")
elif 4 < dage <= 5 :
print ("The given dog age " + str(dage) + " is " + str(round(dage * 7.2) ) + " in human years")
elif 5 < dage :
print ("The given dog age " + str(dage) + " is " + str(36 + 7 * (round(dage - 5.0)) + " in human years")
else:
print ("your input should be a positive number")
except:
print(age, "is an invalid age.")
print(traceback.format_exc())
calculator() # This line calls the calculator function
this code calculates the age of a dog in human years but when it was executed, there was an error in the 24th line (else:)
Solution to your issue: Your code is missing a closing bracket for
str()function in theprintstatement for your lastelif. Here is the correct statement:Improvements: You can also use f-strings to improve readability. See this tutorial for more details. Also, you can simplify the conditions in your elif statements as the lower bound is not needed.
Here is the code using f-strings and with some improvements: