In this Python tutorial, learn to create a Python program to calculate pay gross pay. The Python program must be able to provide in input from the user for hours worked and the rate of pay. If the hours worked are greater than 40, the pay will be the set rate of pay and not over time. However, if the hours worked are greater than 40, the rate of pay must be 1.5 times the rate of regular hourly pay.
Calculate Gross Pay functions
In order to calculate the gross pay, we have created the weeklyPay(hours, wage) function. This function will be called from the input for hours and wage from the user. Once the user has input the data, the function will be called to calculate the pay based on the hours worked and the hourly wage.
ValueError Exception Function
The get_float(prompt) provides an ValueError exception when a user provides invalid input. If the user were to type in abc for the wage, it would provide an output of, “This is an invalid value. Try again.” This is because we provided an input as get_float, but the input needs to be a float in order for the hours and wage to be calculated.
Code Input:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | def weeklyPay(hours, wage): if hours > 40: return 40 * wage + (hours - 40) * wage * 1.5 else: return hours * wage def getFloat(prompt): while True: try: return float(input(prompt)) except ValueError: print("This is an invalid value. Try again. ") hours = getFloat("How many hours did you work? ") wage = getFloat("What was your hourly rate? ") pay = weeklyPay(hours, wage) print(f"Total pay: ${pay:.2f} ") |
User Input:
1 2 | How many hours did you work? 40.8 What was your hourly rate? 9.81 |
Output:
1 | Total gross pay: $404.17 |