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

Python调用displayRent()出现NameError未定义错误求助

公寓租金查询代码NameError问题修复方案

错误根源分析

  • 调用getType()时未接收返回的choice和furnished变量,导致这两个值在全局作用域中未定义,直接传入displayRent()触发NameError。
  • displayRent()调用时参数顺序与函数定义完全不符,函数定义顺序为choice, furnished, deposit, rent,但调用时传参顺序颠倒。
  • 缺少调用determineRent()的步骤,未生成deposit和rent变量,这两个值同样未定义。
  • 选择退出(选项4)后未终止程序,会继续执行后续输入逻辑,引发不必要的错误。

修复后的完整代码

# 显示公寓类型菜单
def menu():
    print("""
    Type of Apartments for rent

          1) Studio
          2) One Bedroom
          3) Two Bedroom
          4) EXIT PROGRAM
          """)

# 获取用户选择的公寓类型及是否需要家具
def getType():
    choicelist = [1,2,3,4]
    choice = int(input("Enter the apartment type you wish to rent (1-3 or 4 to EXIT PROGRAM): "))
    
    # 验证输入合法性
    while choice not in choicelist:
        print("ERROR: Invalid apartment type...MUST be 1-4!")
        choice = int(input("Enter the apartment type you wish to rent (1-3 or 4 to EXIT PROGRAM): "))
    
    if choice == 4:  
        print("""EXITING THE PROGRAM...
Thanks for inquiring about our apartments for rent!""")
        return None, None  # 返回空值标记退出
    
    furnished = input("Do you want the apartment furnished (Y/N)? ").upper()
    # 验证家具选择合法性
    while furnished not in ['Y', 'N']:
        print("ERROR: Invalid input...MUST be Y or N!")
        furnished = input("Do you want the apartment furnished (Y/N)? ").upper()
    
    return choice, furnished

# 根据选择计算租金和押金
def determineRent(choice, furnished):
    deposits = [0, 800, 1000, 1200]
    unfurnished = [0, 1200, 1500, 1800]
    Furnished_ = [0, 1500, 1800, 2050]

    deposit = deposits[choice]
    rent = Furnished_[choice] if furnished == 'Y' else unfurnished[choice]

    return deposit, rent

# 显示租金和押金信息
def displayRent(choice, furnished, deposit, rent):
    description = ["", "Studio", "One-Bedroom", "Two-Bedroom"]
    print("Description:", description[choice], "Furnished" if furnished == "Y" else "Unfurnished")
    print(f"Deposit: ${deposit}")
    print(f"Rent: ${rent}")
    print()

# 主程序逻辑
menu()
choice, furnished = getType()

# 判断是否退出程序
if choice is not None:
    deposit, rent = determineRent(choice, furnished)
    displayRent(choice, furnished, deposit, rent)

关键修复点说明

  1. 接收getType()的返回值:用choice, furnished = getType()获取用户输入的变量,确保这些值在后续逻辑中可用。
  2. 修正displayRent()传参顺序:按照函数定义的顺序传入参数,保证逻辑对应。
  3. 添加退出判断:当用户选择4时,getType()返回None, None,主程序判断后跳过后续计算和显示逻辑,直接结束。
  4. 新增家具输入验证:避免用户输入非Y/N的非法值,增强程序健壮性。
  5. 简化字符串格式化:使用f-string替代format(),让代码更简洁易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 00:57:07