Python – How can I improve this python code to improve negative testing?

How can I improve this python code to improve negative testing?… here is a solution to the problem.

How can I improve this python code to improve negative testing?

I’m new to Python programming and you’ll most likely decipher my code anyway. I want to know how to improve my code to improve negative testing?

ageinmonths = input("Enter your age in months: ")

age = int(ageinmonths,10)
if type(age) == float:
    print("Invalid age format entered")

if type(age) == str:
    print("Invalid age format entered")

years = int(age/12)
months = age%12

print("Your exact age in years and months is",years,"years",months,"months")

The

problem with the above line of code is that when I enter the correct values ex: 56, 48, etc. in months, it works fine.

But if I happen to enter an invalid value, I get an error message like this:

Enter your age in months: Welcome
Traceback (most recent call last):
  File "C:\Users\Srinivas\Documents\python\guess_age.py", line 2, in <module>
    age = int(ageinmonths,10)
ValueError: invalid literal for int() with base 10: 'Welcome'
>>> 

I would like to know how to improve my code to add the correct error message for negative tests for invalid search criteria such as strings, special characters, floats, etc.

I’m using Python 3.6 (32-bit version).

Solution

As mentioned in Reut Sharabani, you can use >try … Except is blocked.
You can do this:

try:
    int("whatever")
except ValueError:
    print("Upss there was a problem")

Note that I just caught one ValueError exception, not all exceptions.

Related Problems and Solutions