'How to fix 'except ValueError' for python?
I am just starting to learn python and getting an error message that the syntax for calling calculator is wrong. Does anyone have any suggestions?
My code:
import traceback
def calculator():
# Get dog age
age = float(input("Input dog years: "))
try :
# Cast to float
d_age = float(age)
except ValueError as e:
print(age, "is an invalid age.")
else:
print(traceback.format_exc())
if (d_age == 1.0):
print("Your dog is 15 years old")
elif (d_age == 2.0):
print("Your dog is 24 years old")
elif (d_age == 3.0):
print("Your dog is, " + str(3.0 * 9.3))
elif (d_age == 4.0):
print("Your dog is " + str(4.0 * 8.0))
elif (d_age == 5.0):
print("Your dog is " + str(5.0*7.2))
else:
print("Your dog is " + str(((d_age-5.0)*7.0)+36)
# If user enters negative number, print message
# Otherwise, calculate dog's age in human years
# your code here
calculator() # This line calls the calculator function
Solution 1:[1]
Perhaps you forgot ")" at line 28?
print("Your dog is " + str(((d_age-5.0)*7.0)+36))
For validating input, you can use the next function that uses string.isnumeric()
method of strings to validate it:
age = input("Input dog years: ")
while True:
if age[0] == "-" and age[1::].isnumeric():
# If the variable is not positive number, ask to type positive
age = input("Age of dog cannot be less than zero, dude: ")
elif not age.isnumeric():
# If the variable is not number at all
age = input("Number, dude, I said I need number: ")
else:
break
Solution 2:[2]
I see the issue... pretty simple. You need a )
at the end of print("Your dog is " + str(((d_age-5.0)*7.0)+36)
, so it should look like this:
print("Your dog is " + str(((d_age-5.0)*7.0)+36))
Solution 3:[3]
You have a missing parenthesis at line 28, column 58...
Solution 4:[4]
That's because you cast to float twice.
You already cast the input in age = float(input("Input dog years: "))
which throws an error if you input a string or something else.
This makes your try-catch obsolete.
Plus you miss a ')' at the end of line 28
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Bauyrzhan Ospan |
Solution 2 | acharb |
Solution 3 | Lukas Laudrain |
Solution 4 | Malsesto |