Python 2.7.16 报Name not defined错误及代码迭代问题求助
问题排查与代码修正
核心错误点
- 变量拼写/未定义问题:
ListIDS拼写错误,对应定义的变量是ListIDsListProperties未初始化,代码中直接调用但开头未定义该列表total_comission未初始化就执行加法操作,触发未定义错误
- 循环逻辑错误:
- 将
employee_num转为字符串后遍历,会逐个字符循环(比如输入"3"只循环1次,输入"10"循环2次),完全不符合“按员工数量循环”的需求 - 遍历
ListProperties时,直接取元素值作为索引使用,导致索引越界或类型错误
- 将
- 冗余初始化:开头给
employee_name、employee_id等变量赋字符串值完全多余,后续会被输入覆盖
修正后的代码
import time # 初始化所有必要的列表与变量 ListNames = [] ListIDs = [] ListProperties = [] ListComissions = [] total_properties = 0 total_comission = 0 highest = 0 # 正确获取员工数量并转为整数 employee_num = int(input("Enter the number of employees: ")) # 按员工数量生成循环 for _ in range(employee_num): employee_name = input("Enter the name of the employee: ") ListNames.append(employee_name) employee_id = input("Enter the ID of the employee: ") ListIDs.append(employee_id) employee_properties = int(input("Enter the number of properties sold by the employee: ")) ListProperties.append(employee_properties) total_properties += employee_properties employee_comission = employee_properties * 500 ListComissions.append(employee_comission) total_comission += employee_comission # 遍历列表索引查找最高销量 for i in range(len(ListProperties)): if ListProperties[i] > highest: highest = ListProperties[i] star = ListProperties.index(highest) print("Top performer:") print(ListNames[star]) print(ListIDs[star]) print(ListProperties[star]) print(ListComissions[star]) # 简化佣金计算逻辑 starcomission = ListComissions[star] * 1.15 print(f"Top performer's total commission (with bonus): {starcomission}") # 遍历所有员工(排除top performer) print("\nOther employees:") for x in range(employee_num): if x != star: print(ListNames[x]) print(ListIDs[x]) print(ListProperties[x]) print(ListComissions[x])
错误说明
- 拼写与定义问题:严格保证变量名一致,所有用到的列表、变量必须提前初始化
- 循环逻辑修正:员工数量转整数后用
range(employee_num)生成对应次数的循环;遍历列表时通过索引访问元素,避免用元素值当索引 - 冗余代码清理:删除不必要的变量初始化,让代码更简洁
内容的提问来源于stack exchange,提问作者Silesviing
相关产品推荐
相关产品推荐

