'Using try except in a function

I'm trying to figure out how to get try/except to work within a function.

Here is what I have now and it produces a traceback error when I enter anything not numeric (e.g. "forty").

def computepay(hours=float(input('Enter hours worked: ')), rate=float(input('Enter hourly rate: '))):
    try:
        if hours <= 40:
         print('pay:', hours * rate)
        else:
            ot_rate = rate * 1.5
            ot_hours = hours - 40
            print('pay: $', (ot_hours * ot_rate) + (40 * rate))
    except NameError:
        print('Error, please enter numeric input')


computepay()


Solution 1:[1]

Your function should not deal with user input. It should deal only with computing and display resilts.

def computepay(hours: float, rate: float) -> None:
  if hours <= 40:
   print('pay:', hours * rate)
  else:
      ot_rate = rate * 1.5
      ot_hours = hours - 40
      print('pay: $', (ot_hours * ot_rate) + (40 * rate))


try:
  hours = float(input('Enter hours worked:'))
  rate = float(input('Enter hourly rate: '))
  computepay(hours,rate)
except ValueError :
  print('input must be numeric')

Solution 2:[2]

You must handle the input errors separately. That way the code can't proceed if the inputs are invalid.

def computepay(hours, rate):
  try:
    if hours <= 40:
     print('pay:', hours * rate)
    else:
        ot_rate = rate * 1.5
        ot_hours = hours - 40
        print('pay: $', (ot_hours * ot_rate) + (40 * rate))


try:
    var hours = float(input('Enter hours worked: '))
    var rate = float(input('Enter hourly rate: '))
    computepay(hours, rate)
except ValueError:
    print('Error, please enter numeric input')

Hope this helps.

Solution 3:[3]

You can handle the user's input within the function; when you try to convert as an argument there is no mechanism to support the possibility that the input is not a floating value.

def computepay(hours=(input('Enter hours worked: ')), rate=(input('Enter hourly rate: '))):
    try: 
        hours = float(hours)  
        rate = float(rate)            
        if hours <= 40:
            print('pay:', hours * rate)
        else:
            ot_rate = rate * 1.5
            ot_hours = hours - 40
            print('pay: $', (ot_hours * ot_rate) + (40 * rate))
    except ValueError:
        print('Error, please enter numeric input')


computepay()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 balderman
Solution 2
Solution 3