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

Python如何避免调用函数后变量与列表被重置?

解决Python电影管理程序的变量重置问题

核心问题分析

你的代码里有几个关键问题导致变量被重置:

  1. main函数内部每次执行都会强制把movieNameList、moviePriceList设为空列表,x设为0——不管你传入什么参数,都会被这几行代码覆盖。
  2. addMovie里选择返回菜单时直接调用main(),没有把当前已修改的列表和x传进去,导致新启动的main又重新初始化所有变量。
  3. 还有几个小bug:while循环条件用了and(应该是or,价格不可能同时>=13和<=5),moviePriceList.pop少了括号,main函数的参数名写错(movieRentalList应为moviePriceList),调用main()时没传参数。

修改方案

1. 重构main函数,避免强制初始化

把变量初始化放到参数默认值里,第一次调用用空列表和0,后续调用传入已有的数据,不会被重置:

def main(movieNameList=None, moviePriceList=None, x=0):
    # 仅第一次调用时初始化空列表
    if movieNameList is None:
        movieNameList = []
    if moviePriceList is None:
        moviePriceList = []
    
    menu = input("Input '1' to add a movie to the store\n" \
                 + "Input '2' to view the list of movies\n" \
                 + "Input '3' to end the programme\n" \
                 + ">>> ")
    if menu == "1":
        # 接收addMovie返回的更新后的数据
        movieNameList, moviePriceList, x = addMovie(movieNameList, moviePriceList, x)
        # 处理完添加后,带新数据回到main菜单
        main(movieNameList, moviePriceList, x)
    elif menu == "2":
        # 实现查看电影列表的逻辑
        print("\nMovie List:")
        if not movieNameList:
            print("No movies in the store yet.")
        else:
            for idx, name in enumerate(movieNameList):
                print(f"{idx+1}. {name} - ${moviePriceList[idx]} NZD")
        # 查看完回到菜单
        main(movieNameList, moviePriceList, x)
    elif menu == "3":
        print("Programme ended.")
        return

2. 修改addMovie函数,避免递归调用main导致重置

移除addMovie里的main()调用,直接返回更新后的数据,让main函数自己处理菜单循环:

def addMovie(movieNameList, moviePriceList, x):
    movieName = input("Name of Movie\n>>> ")
    movieNameList.append(movieName)
    
    # 修正价格输入逻辑,处理非整数输入和无效范围
    while True:
        try:
            price = int(input(f"How much would you like to rent {movieName} for? ($6-12 NZD)\n>>> "))
            if 6 <= price <= 12:
                moviePriceList.append(price)
                break
            else:
                print("Invalid Input: Price must be between 6 and 12 NZD")
        except ValueError:
            print("Invalid Input: Please enter an integer number")
    
    x += 1
    print(f"\nCurrent movie count: {x}")
    print("Movie Names:", movieNameList)
    print("Movie Prices:", moviePriceList)
    
    menu = input("\nInput '1' to add another movie to the store\n" \
                 + "Input '2' to return to the menu\n>>> ")
    if menu == "1":
        # 递归添加,返回更新后的数据
        return addMovie(movieNameList, moviePriceList, x)
    elif menu == "2":
        # 返回当前更新后的数据,回到main菜单
        return movieNameList, moviePriceList, x

3. 正确启动程序

调用main()时不需要传参数,第一次会用默认值初始化:

if __name__ == "__main__":
    main()

修改后的完整代码

def addMovie(movieNameList, moviePriceList, x):
    movieName = input("Name of Movie\n>>> ")
    movieNameList.append(movieName)
    
    while True:
        try:
            price = int(input(f"How much would you like to rent {movieName} for? ($6-12 NZD)\n>>> "))
            if 6 <= price <= 12:
                moviePriceList.append(price)
                break
            else:
                print("Invalid Input: Price must be between 6 and 12 NZD")
        except ValueError:
            print("Invalid Input: Please enter an integer number")
    
    x += 1
    print(f"\nCurrent movie count: {x}")
    print("Movie Names:", movieNameList)
    print("Movie Prices:", moviePriceList)
    
    menu = input("\nInput '1' to add another movie to the store\n" \
                 + "Input '2' to return to the menu\n>>> ")
    if menu == "1":
        return addMovie(movieNameList, moviePriceList, x)
    elif menu == "2":
        return movieNameList, moviePriceList, x

def main(movieNameList=None, moviePriceList=None, x=0):
    if movieNameList is None:
        movieNameList = []
    if moviePriceList is None:
        moviePriceList = []
    
    menu = input("Input '1' to add a movie to the store\n" \
                 + "Input '2' to view the list of movies\n" \
                 + "Input '3' to end the programme\n" \
                 + ">>> ")
    if menu == "1":
        movieNameList, moviePriceList, x = addMovie(movieNameList, moviePriceList, x)
        main(movieNameList, moviePriceList, x)
    elif menu == "2":
        print("\nMovie List:")
        if not movieNameList:
            print("No movies in the store yet.")
        else:
            for idx, name in enumerate(movieNameList):
                print(f"{idx+1}. {name} - ${moviePriceList[idx]} NZD")
        main(movieNameList, moviePriceList, x)
    elif menu == "3":
        print("Programme ended.")
        return

if __name__ == "__main__":
    main()

关键修改说明

  • main函数仅在第一次调用时初始化变量,后续调用传入已更新的数据,彻底避免重置。
  • addMovie不再直接调用main(),而是返回更新后的状态,由main递归调用自己并携带新数据,保持状态连续。
  • 修复了价格输入的逻辑漏洞,包括处理非整数输入和无效范围的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 12:37:55