Python Forum

Full Version: Python- Help with try: input() except ValueError: Loop code to start of sequence
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Good Evening,
I have been learning python for about a week now and decided to try and write a financial calculator program (however painstaking due to my complete lack of knowledge. I am having trouble with user input and try:. I would like to restart the program back to user input when the user inputs a str or float rather than an int. I can get the program to print "please use a real number" if they input something other than an int, but I don't know how to get it to restart.

I know my code is probably dreadfully inefficient, and I am still working the calculation at the end for compound interest. (Help appreciated there too!)

Respectfully yours,
Aldi
try:
    age = int(input("What is your age?"))
    retirement_age = int(input("At what age would you like to retire?"))
except ValueError:
    print("Please use a whole number")
years_to_save = int(retirement_age-age)
print(f'You have {years_to_save} years to save.')
try:
    mnth_svng_no_intrest = int(input("How much money will you save per month?"))
except ValueError:
    print("Use a real number, rounded to the tenth")
life_svng_no_intrest = int(years_to_save*mnth_svng_no_intrest)*12
print(f'That is great! If you do NOTHING but save that money, you will have ${life_svng_no_intrest} at retirement.')
interst_at_ten = (mnth_svng_no_intrest(1*.1)**1)
this should give you the idea on how to loop a code when error occured
while True:
    try:
        variable = int(input())
        break
    except:
        print("try again")
Actually, the except clause should be qualified.
if you don't know what type of exception, you can find out as follows:
following will intentionally create an exception:
>>> def get_numbase():
...     numbase = 0
...     try:
...         numbase = int(input('Enter numbase: '))
...         return numbase
...     except:
...         print("Unexpected error:", sys.exc_info()[0])
...
>>> get_numbase()
Enter numbase: how about this
Unexpected error: <class 'ValueError'>
So this will show what type of exception is being thrown.

You can then correct your code as follows (yo can remove the import sys):
>>> def get_numbase():
...     numbase = 0
...     while True:
...         try:
...             numbase = int(input('Enter number base: '))
...             return numbase
...         except ValueError:
...             print('Please enter numeric number base')
...
>>> get_numbase()
Enter number base: How about this
Please enter numeric number base
Enter number base: 10
10
>>>
Now, if some exception other than ValueError occurs, you will still get a traceback, but
Value Error will be properly captured and delt with