使用 if 语句时出现名称错误 - Python 2.7

Name Error while using if statements - 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

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?

非常感谢!

您需要使用字符串而不是变量:

if user_seating == 'economy':

按照您的方式,Python 正在寻找在您的代码中声明的名为 economy 的实际变量(NameError 告诉您没有)。

economybusiness 被视为变量。你必须让它们成为字符串才能工作。

如消息所述:您从未定义变量 economy。您似乎打算将 user_seating 字符串值 economy 进行比较;如果是这种情况,您需要将其括在引号中。

您只需要将经济放在引号内即

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

当然也可以为您的其他 if 语句执行此操作。您还应该考虑在检查相等性之前让用户输入小写。