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

时间:2015-03-05 01:23:28

标签: python if-statement input while-loop

我目前正在开展一个充当航班预订系统的项目。截至目前,我在计算和显示if 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

正如我上面所说的,我试图根据用户选择的班级(经济舱,商务舱和头等舱)以及所需行李所需的总数来增加预订机票的总价格。办理登机手续(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语句之外定义seat_total?

非常感谢你!

4 个答案:

答案 0 :(得分:3)

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

if user_seating == 'economy':

你拥有它的方式,Python正在寻找一个在你的代码中声明的名为economy的实际变量(没有NameError告诉你的那样)。

答案 1 :(得分:2)

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

答案 2 :(得分:2)

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

答案 3 :(得分:2)

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

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

当然也可以为你的其他if语句做到这一点。在检查相等性之前,您还应考虑将用户输入小写。