This is a simple payroll program that computes pay with overtime.
My goal was to use try
/except
and def
to start over if letters are input instead of numbers.
def payroll():
hrs = input("Enter Hours:")
try:
hrs = int(hrs)
except:
print('ERROR: use numbers, not letters to write numbers. start over')
payroll()
h = float(hrs)
#r = float(rate = input("enter rate:")) <= nested doesn't work
rate = input("enter rate:")
try:
rate = int(rate)
except:
print('ERROR: use numbers, not letters to write numbers. start over')
payroll()
r = float(rate)
paylow = r*h
if h <= 40: pay = paylow
else: pay = 40*r+r*1.5*(h-40)
print("pay: $",pay)
payroll()
If I input numbers on the first try, it executes flawlessly. If I input letters it starts over fine, but once it has, and I then input numbers, it will successfully execute and display pay, but followed by a traceback and a value error:
Enter Hours:g
ERROR: use numbers, not letters to write numbers. start over
Enter Hours:5
enter rate:5
pay: $ 25.0
Traceback (most recent call last):
File "tryexcept.py", line 24, in <module>
payroll()
File "tryexcept.py", line 11, in payroll
h = float(hrs)
ValueError: could not convert string to float: 'g'
How do I interpret the error? And what can I do to fix the issue?
In the except clause, you need to return:
except:
print('ERROR: use numbers, not letters to write numbers. start over')
payroll()
return
Otherwise, once your inner payroll returns, you will continue with the rest of the program.
Note: I would also not recommend this form of programming. It creates needless stacks, and if you are logging errors etc, it will be really difficult to follow, bot for you, and for other team members looking through the stack trace.
If you are learning about recursion, you should look up "tail-recursion" which is an efficient form of recursion. Unfortunately it is not supported by Python.