Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I improve this python code for improved negative testing?

I am a newbie to Python programming which you will most likely decipher seeing my code anyways. I would like 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 it works fine when I enter the proper value ex: 56 , 48 etc. in months.

But if I happen to enter an invalid value, I get an error message shown below:

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 a proper error message for negative testing for invalid search criteria such as Strings, Special characters, floats etc.

I am using Python 3.6 (32 bit version).

like image 243
srini Avatar asked Sep 21 '26 09:09

srini


1 Answers

As Reut Sharabani mentioned, you could use a try ... except block. You could do something like:

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

Note that I'm just catching a ValueError exception, and not all exceptions.

like image 168
sainoba Avatar answered Sep 23 '26 22:09

sainoba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!