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

Python程序选择3时字典无限循环问题排查求助

问题定位与解决方案

核心问题:外层循环未更新选择值

你看到的「无限遍历字典」并非for workerID,workername in workerdict.items()的问题,而是外层while choice != 5循环在重复执行。当选择选项3后,代码完成字典遍历输出,但没有重新获取用户的新选择,choice变量一直保持为3,导致外层while循环不断进入choice==3的分支,看起来像是字典遍历无限循环。

修复方法

将菜单显示、选择输入的逻辑放到while循环内部,确保每次操作后都会重新提示用户选择,避免停留在同一个选择值导致循环重复执行。同时修复原代码中的其他逻辑漏洞:

完整修复后的代码

workerdict = {101:'Fred', 103:'Barney Stone', 106:'Wilma Flint', 109:'Betty Rubble', 112:'Dino Dawg'}

def checkID(id):
    return id in workerdict

def calculatePay(hourWork,hourWage):
    global weeklypay
    overtime = 0  # 初始化 overtime,避免未定义就使用
    if hourWork > 40:
        overtime = (hourWork - 40)*(hourWage*1.5)
    weeklypay = (hourWork*hourWage) + overtime
    return weeklypay

def calculateTax(wage):
    global weeklypay
    # 修正判断条件与返回值:原代码返回传入的wage而非计算的税费
    if weeklypay < 300:
        Tax = weeklypay*0.10
    elif weeklypay < 600:
        Tax = weeklypay*0.12
    elif weeklypay < 900:
        Tax = weeklypay*0.15
    elif weeklypay < 1200:
        Tax = weeklypay*0.20
    else:
        # 补充工资>=1200的边界处理
        Tax = weeklypay*0.25
    return Tax

def main():
    workerList = []
    idList = []
    overhourlist = []
    overpaylist = []

    while True:
        # 每次循环都重新显示菜单并获取选择
        print("Choice Options")
        print("\t1. Add Workers")
        print("\t2. Process Worker")
        print("\t3. Display All Workers ID and Name")
        print("\t4. Display Processed Workers")
        print("\t5. End Program")
        print()
        
        # 获取并验证用户选择
        try:
            choice = int(input("Input choice: "))
        except ValueError:
            print("Please enter a valid number")
            continue
        
        while choice < 1 or choice > 5:
            choice = int(input("Invalid choice enter a number between 1 and 5, Input choice: "))
        
        # 选择5则退出程序
        if choice == 5:
            break
        
        if choice == 1:
            workerID = int(input("Enter a worker ID: "))
            # 循环检查直到输入未使用的ID
            while checkID(workerID):
                workerID = int(input("Enter a unused worker ID: "))
            workername = input("Enter the worker name: ")
            workerdict[workerID] = workername

        elif choice == 2:
            workerID = int(input("Enter a worker ID: "))
            if not checkID(workerID):
                print("Worker ID does not exist!")
                continue
            # 验证工时输入合法性
            hourWork = float(input("Enter hours worked: "))
            while hourWork < 0:
                print("Enter a valid positive time worked")
                hourWork = float(input("Enter hours worked: "))
            # 验证时薪输入合法性
            hourWage = int(input("Enter hourly wage: "))
            while hourWage < 0:
                print("Enter a valid positive wage")
                hourWage = int(input("Enter hourly wage: "))
            
            weeklypay = calculatePay(hourWork,hourWage)
            tax = calculateTax(weeklypay)
            netpay = weeklypay - tax
            
            worker = f"{workerID},{workerdict[workerID]},{weeklypay}"
            workerList.append(worker)
            idList.append(str(workerID))
            
            overtimehour = hourWork - 40 if hourWork > 40 else 0
            overhourlist.append(str(overtimehour))
            overtimepay = (hourWork - 40)*(hourWage*1.5) if hourWork > 40 else 0
            overpaylist.append(str(overtimepay))

        elif choice == 3:
            for workerID,workername in workerdict.items():
                print(f"ID: {workerID}, Name: {workername}")

if __name__ == "__main__":
    main()

关键修复点说明

  1. 外层循环逻辑调整:将菜单显示、选择输入放入while True循环,每次操作后重新获取用户选择,避免停留在同一选择值导致无限循环。
  2. 修复calculatePay函数:先初始化overtime,再根据工时判断计算,避免未定义变量报错。
  3. 修复calculateTax函数:返回计算后的税费而非传入的工资值,补充工资>=1200的边界处理。
  4. 完善输入验证:对新增员工ID、工时、时薪等输入添加循环验证,确保输入合法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 18:06:06