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

Python 2.7假期费用计算程序报错求助:NameError问题排查

Hey there! Let's figure out why you're hitting that NameError and get your holiday cost calculator working properly.

What's Causing the NameError?

The issue is super straightforward: when you call hotel_cost(), plane_cost(), and car_rental() in your code, you're running the functions but not saving their return values to the nights, city, and days variables that holiday_cost() expects. Python has no idea what those variable names refer to when you try to pass them later, hence the error.

Fixing the Code (Plus a Few Extra Improvements)

Here's a corrected version of your code with explanations of the changes:

def hotel_cost(nights):
    return nights * 875

def plane_cost(city):
    ticket = 0
    # Removed the unnecessary while loop that was causing unexpected behavior
    if city == '1':
        ticket = 750
    elif city == '2':
        ticket = 850
    elif city == '3':
        ticket = 600
    else:
        print 'You have selected an invalid option'
        ticket = 0  # Ensure we always return a number, not None
    return ticket

def car_rental(days):
    return days * 275

def holiday_cost(nights, city, days):
    # Used clearer variable names instead of overwriting the input parameters
    hotel_total = hotel_cost(nights)
    plane_total = plane_cost(city)
    car_total = car_rental(days)
    return hotel_total + plane_total + car_total

# KEY FIX: Assign the function results to the variables we'll use later
nights = int(raw_input('How many nights will you be staying? '))
city = raw_input('\n1. O.R. Tambo International\n2. Capetown International\n3. King Shaka International\nWhere you flying to? ')
days = int(raw_input('How many days will you need a car for?: '))

total = holiday_cost(nights, city, days)
print "Total holiday cost: R{}".format(total)

Breakdown of Changes

  1. Fixed the Variable Definition Issue:
    We now assign the output of each function call to the nights, city, and days variables. This gives Python concrete values to pass to holiday_cost().

  2. Cleaned Up the plane_cost Function:

    • Removed the redundant while loop that would have caused infinite loops if the user entered an invalid option.
    • Added a ticket = 0 in the else block to ensure the function always returns a numeric value (instead of None), which prevents a TypeError when calculating the total cost.
  3. Improved Readability in holiday_cost:
    Instead of overwriting the input parameters (nights = hotel_cost(nights)), we use separate variables like hotel_total to make the code easier to follow.

Now when you run the code, it should correctly calculate and display your total holiday cost without any errors!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:35:31