-2

我不断收到此错误:

UnboundLocalError:分配前引用的局部变量“tickets_per_person”。

但是,我已将变量分配tickets_per_person为代码顶部的全局变量,所以我不明白为什么它没有被识别。

完整的功能是:

def date_price_increase() :
    if 'July' or 'August' or 'September' in full_date :
        tickets_per_person = tickets_per_person * 1.15
    elif 'February' or 'October' or 'November'in full_date :
        tickets_per_person = tickets_per_person * 0.95
    else :
        tickets_per_person = tickets_per_person    

分配全局变量:

global tickets_per_person
tickets_per_person = 0

回溯是:

Exception in Tkinter callback
Traceback (most recent call last):
  File 
"C:\Users\samue\AppData\Local\Programs\Thonny\lib\tkinter\__init__.py", 
line 1705, in __call__
    return self.func(*args)
  File "C:\Users\samue\OneDrive - The Becket 
School\Airport_Tkinters_GUI_29.12.18.py", line 485, in cost
    date_price_increase()
  File "C:\Users\samue\OneDrive - The Becket 
School\Airport_Tkinters_GUI_29.12.18.py", line 325, in date_price_increase
   tickets_per_person = tickets_per_person * 1.15
UnboundLocalError: local variable 'tickets_per_person' referenced before 
   assignment
4

1 回答 1

2

您必须使用global tickets_per_personinsidedef date_price_increase():来通知函数您要使用全局变量tickets_per_person而不是本地变量。

def date_price_increase() :

    global tickets_per_person

    if 'July' or 'August' or 'September' in full_date :
        tickets_per_person = tickets_per_person * 1.15
    elif 'February' or 'October' or 'November'in full_date :
        tickets_per_person = tickets_per_person * 0.95
    else :
        tickets_per_person = tickets_per_person   

不需要global在函数外部使用单词,因为在函数外部创建的所有变量都是全局的。


编辑:您应该使用参数和创建普通函数return。它是首选方法。

def date_price_increase(tickets_per_person, full_date):

    if 'July' or 'August' or 'September' in full_date:
        tickets_per_person = tickets_per_person * 1.15
    elif 'February' or 'October' or 'November'in full_date:
        tickets_per_person = tickets_per_person * 0.95
    else:
        tickets_per_person = tickets_per_person   

    return tickets_per_person

并运行

tickets_per_person = date_price_increase(tickets_per_person, full_date)
于 2019-05-01T12:04:19.997 回答