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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With