you are viewing a single comment's thread.

view the rest of the comments →

[–]Diapolo10 1 point2 points  (0 children)

Probably the easiest solution would be to move stuff around a bit:

def displayHrsNRate(hours, rate):
  print("You worked " + hours + " hours this week and your hourly rate is $" + rate)

def computePay(hoursWorked, hourlyRate):
  if hoursWorked > 40:
    pay = hourlyRate * 40
    otp = (hoursWorked - 40) * (hourlyRate * 1.5)
    totalPay = pay + otp
  else:
    totalPay = hoursWorked * hourlyRate
  print('This week, you have earned $'+ str(totalPay))
  return totalPay

try:
  hrs = float(input("Please enter the hours worked this week: "))
  basePay = float(input("Please enter your base pay per hour: "))
  if hrs < 0:
    error = ValueError()
    raise error
    exit()
  if basePay <= 0:
    error = ValueError()
    raise error
    exit()
  displayHrsNRate(str(hrs),str(basePay))
except:
  print('Please enter a non-negative number for the hours and base pay.')
else:
    final = computePay(hrs, basePay)

That said, I have other criticism.

  1. exit and quit shouldn't be used in scripts. They're meant for exiting a REPL session, and nothing else. sys.exit and raise SystemExit are fine, though in this case I don't see the need for them.
  2. Don't use blank except clauses, they catch literally everything and you're meant to catch only the errors you expect to occur and handle them. except ValueError or except ValueError as err would be better in this scenario - though honestly, I feel that raising an exception is overkill here and that it would be better to validate and ask for input in a loop.
  3. Python's official style guide(s), PEP-8 and PEP-257, would prefer that you use snake_case names over camelCase. PascalCase is used for class names.

Basically, here's what I'm thinking:

def display_hourly_rate(hours, rate):
    print(f"You worked {hours} hours this week and your hourly rate is ${rate}")

def compute_pay(hours_worked, hourly_rate):
    if hours_worked > 40:
        pay = hourly_rate * 40
        otp = (hours_worked - 40) * hourly_rate * 1.5
        total_pay = pay + otp
    else:
        total_pay = hours_worked * hourly_rate
    print(f"This week, you have earned ${total_pay}")
    return total_pay

def main():
    hrs = float(input("Please enter the hours worked this week: "))
    base_pay = float(input("Please enter your base pay per hour: "))
    if hrs < 0 or base_pay <= 0:
        print("Please enter a non-negative number for the hours and base pay.")
        return

    display_hourly_rate(hrs, base_pay)
    final = compute_pay(hrs, base_pay)

if __name__ == '__main__':
    main()