简体   繁体   中英

Why the traceback error with a try/except recursive(?) function?

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.

in a further iteration of the program i utilized 'while' and 'break' instead of 'def' and 'return' to achieve the same results.

while True:
    hrs = input("Enter Hours:")
    try:
        hrs = int(hrs)
        break
    except:
        print('ERROR: use numbers, not letters to write numbers. try again')
h = float(hrs)
while True:
    rate = input("enter rate:")
    try:
        rate = int(rate)
        break
    except:
        print('ERROR: use numbers, not letters to write numbers. try again')
r = float(rate)
paylow = r*h
if h <= 40: pay = paylow
else:
    print("overtime pay alert!")
    pay = 40*r+r*1.5*(h-40)
print("pay: $",pay)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM