Python课程作业程序运行报TypeError 无法定位错误原因求助
代码报错原因及修复方案
核心错误点
input函数仅支持传入1个字符串作为提示语,原代码给input传入了3个独立参数(提示文本、周数变量、后缀文本),触发参数数量不匹配的TypeError,需要先把多个内容拼接为一个字符串再传给input。- 自定义的
regularPay、overtimePay函数要求传入3个参数,原代码调用时没有传任何参数,后续还直接把函数名当成返回值做运算,属于语法错误。 overtimePay函数内部误用了不存在的变量regularWorkWeek,实际定义的参数名是regWorkWeek,变量名拼写不匹配会触发未定义报错。- for循环的遍历对象写为
(1, weeksWorked + 1)是二元组,只会循环2次,要遍历指定范围的周数需要用range(1, weeksWorked + 1)。 overtimePay函数没有处理无加班的场景,此时会默认返回None,后续参与数值运算会报错,需要补充无加班时返回0的逻辑。- 打印语句多余套用了
float()函数,把字符串和数值混合传入float()会触发类型错误,直接调用print输出即可。
修正后完整代码
payPerHour = float(input("How much do you make per hour?\n")) regWorkWeek = float(input("How many hours is a regular work week for you?\n")) overtimeRate = float(input("What do you make for overtime pay?\n")) weeksWorked = int(input("How many weeks will you be working?\n")) def regularPay(payPerHour, regWorkWeek, hoursWorked): if hoursWorked < regWorkWeek: return payPerHour * hoursWorked else: return payPerHour * regWorkWeek def overtimePay(payPerHour, regWorkWeek, hoursWorked, overtimeRate): if hoursWorked > regWorkWeek: return (payPerHour * overtimeRate) * (hoursWorked - regWorkWeek) else: return 0 for currentWeek in range(1, weeksWorked + 1): hoursWorked = int(input(f"How many hours did you work in week {currentWeek} ?\n")) # 调用函数传入对应参数,接收返回值 reg_pay = regularPay(payPerHour, regWorkWeek, hoursWorked) over_pay = overtimePay(payPerHour, regWorkWeek, hoursWorked, overtimeRate) totalPay = reg_pay + over_pay print(f"Week {currentWeek} pay= ${reg_pay:.2f},\n") print(f"Overtime pay= ${over_pay:.2f},\n") print(f"total pay= ${totalPay:.2f}.")
内容的提问来源于stack exchange,提问作者Jesse Proctor
相关产品推荐
相关产品推荐

