You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 2.7.16 报Name not defined错误及代码迭代问题求助

问题排查与代码修正

核心错误点

  • 变量拼写/未定义问题:
    • ListIDS 拼写错误,对应定义的变量是 ListIDs
    • ListProperties 未初始化,代码中直接调用但开头未定义该列表
    • 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])

错误说明

  1. 拼写与定义问题:严格保证变量名一致,所有用到的列表、变量必须提前初始化
  2. 循环逻辑修正:员工数量转整数后用range(employee_num)生成对应次数的循环;遍历列表时通过索引访问元素,避免用元素值当索引
  3. 冗余代码清理:删除不必要的变量初始化,让代码更简洁

内容的提问来源于stack exchange,提问作者Silesviing

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 01:15:36