How do I improve this python code for improved negative testing? -
i newbie python programming decipher seeing code anyways. know how improve code improve negative testing?
ageinmonths = input("enter 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 , months is",years,"years",months,"months") the problem above line of code works fine when enter proper value ex: 56 , 48 etc. in months.
but if happen enter invalid value, error message shown below:
enter 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 int() base 10: 'welcome' >>> i know how improve code add proper error message negative testing invalid search criteria such strings, special characters, floats etc.
i using python 3.6 (32 bit version).
as reut sharabani mentioned, use try ... except block. like:
try: int("whatever") except valueerror: print("upss there problem") note i'm catching valueerror exception, , not exceptions.
Comments
Post a Comment