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
Fixed the Variable Definition Issue:
We now assign the output of each function call to thenights,city, anddaysvariables. This gives Python concrete values to pass toholiday_cost().Cleaned Up the
plane_costFunction:- Removed the redundant
whileloop that would have caused infinite loops if the user entered an invalid option. - Added a
ticket = 0in theelseblock to ensure the function always returns a numeric value (instead ofNone), which prevents aTypeErrorwhen calculating the total cost.
- Removed the redundant
Improved Readability in
holiday_cost:
Instead of overwriting the input parameters (nights = hotel_cost(nights)), we use separate variables likehotel_totalto 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

