1
def pay():
  hours = input("Enter hours: ")
  rate = input("Enter rate: ")
  try:
    hours = int(hours)
    rate = int(rate)
  except:
    print("Not a valid number!")
    return pay()

  if hours > 40: rate *= 1.5
  return "Pay: $" + str(hours * rate)

print(pay())

The above function works, but I was wondering how can we use recursion if the input in not an int.

Should I even use inputs here? I'm new to python and programming in general.

I recon we shouldn't use inputs when not required. Right?

  • Check out [Asking the user for input until they give a valid response](https://stackoverflow.com/q/23294658/3890632) – khelwood Aug 25 '21 at 11:14
  • You should not use recursion here. Use a ```while``` loop instead –  Aug 25 '21 at 11:14
  • Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) –  Aug 25 '21 at 11:15
  • By the way, are you sure you get 1.5 times the rate for the whole lot, and not just the amount of time you go over 40? Like if you work 41 hours you'd expect to get 40 hours at normal rate and 1 hour at 1.5 rate. Not 1.5 rate for the whole 41 hours. – khelwood Aug 25 '21 at 11:17
  • *"Should I even use inputs here"* No, you shouldn't. As much as possible you should separate the logic of the calculations from the input/out part of the code. Write a first function `pay(hours, rate)` that expects two numbers and returns a number; then write a second function that asks for user input, calls `pay` with the appropriate arguments, and prints out the result. – Stef Aug 25 '21 at 13:15
  • Since your code kinda works but you'd like to make it better, this question would probably be better suited for https://codereview.stackexchange.com/ than for stackoverflow. – Stef Aug 25 '21 at 13:17

1 Answers1

-1

Use While instead Recursive function for this

example:

def pay():
  hours = input("Enter hours: ")
  while not hours.isdigit():
    hours = input("Not Digit, Enter hours: ")
  rate = input("Enter rate: ")
  while not rate.digit():
    rate = input("Not Digit, Enter rate: ")
  if hours > 40: rate *= 1.5
  return "Pay: $" + str(hours * rate)

print(pay())
gaetan1903
  • 34
  • 3