script_18.py - Working Hours Validator
Code
#!/usr/bin/env python3
"""Working hours validator"""
hours = float(input("Enter hours worked: "))
if hours < 0:
print("Invalid: hours cannot be negative")
elif hours <= 40:
pay = hours * 15
print(f"Regular pay: ${pay:.2f}")
else:
regular_pay = 40 * 15
overtime_pay = (hours - 40) * 22.50
print(f"Regular pay: ${regular_pay:.2f}")
print(f"Overtime pay: ${overtime_pay:.2f}")
print(f"Total pay: ${regular_pay + overtime_pay:.2f}")
Explanation
Line 4: hours = float(input("Enter hours worked: "))
- float() allows decimal hours like 7.5 or 40.25
- hours variable is float type
Line 6: if hours < 0:
- Input validation - checks for invalid negative hours
- Guard clause catches errors before calculations
- Good practice to validate input early
Line 8: elif hours <= 40:
- <= means less-than-or-equal
- Checks if hours are within regular time (40 hours or less)
- Range is 0 to 40 (inclusive)
Line 9: pay = hours * 15
- * multiplication operator
- 15 is the hourly rate (integer literal)
- Result is float (float * int = float)
- pay variable stores calculated float
Line 12: regular_pay = 40 * 15
- Fixed calculation for 40 hours at regular rate
- Always 600.0 for overtime scenarios
- 40 and 15 are integer literals, but result is stored as float
Line 13: overtime_pay = (hours - 40) * 22.50
- Parentheses ensure subtraction before multiplication
- hours - 40 calculates overtime hours only
- 22.50 is float literal (overtime rate: 1.5x regular)
- Example: 45 hours = 5 overtime hours × $22.50 = $112.50
Line 16: print(f"Total pay: ${regular_pay + overtime_pay:.2f}")
- Addition happens inside f-string placeholder
- + operator adds two float values
- Result formatted to 2 decimal places for currency