Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: error handling with recursive function in error

This is my third question. I've already been voted off of the island twice now on stack overflow, so I'm feeling a little iffy about posting.

Can someone please tell me what is wrong with the below code.

So I have a reference to a function within an error. That is to say, if an error occurs, then the code re-references the function it is entered it runs again. However, when I run it the second time I find that the function does not return the value if both of the inputs are correct (numeric) inputs.

    #This is a program that is designed to calculate gross pay:

def main():
    payment = input2()
    print('Gross pay: $', format(payment, ',.2f'), sep='')

def input2():
    try:
        #we're first getting the number of hours that the user is working.

        hours = int(input("How manyu hours did you work?: "))

        pay_rate = int(input("Enter your hourly payrate here: "))

        #display the gross pay
        gross_pay = hours * pay_rate
        payment = gross_pay
        #display the gross pay:
    except ValueError:
        print('Error: Nope')
        input2()
        return payment
like image 513
Steve Avatar asked May 04 '18 03:05

Steve


1 Answers

IMHO this is not a good use of recursion, a simple while loop would do:

def input2():
    while True:
        try:
            #we're first getting the number of hours that the user is working.
            hours = int(input("How manyu hours did you work?: "))
            pay_rate = int(input("Enter your hourly payrate here: "))

            #display the gross pay
            gross_pay = hours * pay_rate
            return gross_pay
        except ValueError:
            print('Error: Nope')

To fix your recursive call would look like:

def input2():
    try:
        #we're first getting the number of hours that the user is working. 
        hours = int(input("How manyu hours did you work?: "))
        pay_rate = int(input("Enter your hourly payrate here: "))

        #display the gross pay
        gross_pay = hours * pay_rate
    except ValueError:
        print('Error: Nope')
        gross_pay = input2()

    return gross_pay
like image 132
AChampion Avatar answered Sep 28 '22 09:09

AChampion