Home > Enterprise >  How to fix 'except ValueError' for python?
How to fix 'except ValueError' for python?

Time:04-03

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

CodePudding user response:

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

CodePudding user response:

You have a missing parenthesis at line 28, column 58...

CodePudding user response:

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

  • Related