在 if-elif-else 语句中定义值时打印小计?名称错误问题 [Python 2.7]

Printing a subtotal when a value is defined inside an if-elif-else statement? Name error issue [Python 2.7]

我目前正在从事一个作为机票预订系统的项目。截至目前,我在计算和显示小计时遇到问题,小计是在 if elif else 循环语句内部计算的,如果这有意义的话。

比如我现在需要计算座位和行李的小计。下面是我的代码:

user_people = int(raw_input("Welcome to Ramirez Airlines!  How many people will be flying?"))
user_seating = str(raw_input("Perfect!  Now what type of seating would your party prefer?"))
user_luggage = int(raw_input("Thanks.  Now for your luggage, how many bags would you like to check in?"))
user_frequent = str(raw_input("Got it.  Is anyone in your party a frequent flyer with us?"))
user_continue = str(raw_input("Your reservation was submitted successfully.  Would you like to do another?"))
luggage_total = user_luggage * 50


import time
print time.strftime("Date and time confirmation: %Y-%m-%d %H:%M:%S")

if user_seating == 'economy':
    seats_total = user_people * 916
    print seats_total

elif user_seating == 'business':
    seats_total = user_people * 2650
    print seats_total

else: 
    print user_people * 5180

print luggage_total

print luggage_total + seats_total

正如我上面所说,我正在尝试添加根据用户选择class(经济舱、商务舱和头等class)预订的机票数量的总价以及需要托运的所需行李总金额(x 金额 & 50 美元)。

这是我在执行上述代码时收到的错误:

Traceback (most recent call last):
  File "C:/Users/Cory/Desktop/Project 1.py", line 26, in <module>
    print luggage_total + seats_total
NameError: name 'seats_total' is not defined

如何在 if-elif-else 语句之外定义 seats_total?

非常感谢!

那么,您的变量 seats_total 将仅为 user_seating == 'economy'user_seating == 'business' 定义。对于第三种情况,没有定义这样的变量。要定义 "seats_total outside of the if-elif-else statements",只需将其设置为零,例如,或某个默认值。