2017-02-08 115 views
-1

我不知道定義變量的規則。 爲什麼不能工作? 有沒有一種方法可以將多個變量從一個函數發送到另一個函數,還是需要重新定義每個函數中的變量以使它們最後一個?通過函數發送多個變量

def first(): 
    great = 1 
    print(great) 
    second() 

def second(great): 
    # Do I need to re-define great here 
    if great == 1: 
    cool = 3001 
    third(great, cool) 

def third(great, cool): 
    if great > 1: 
    print(cool) 
    # To make great = 1 here? 

first() 
+0

[Python的全局/本地變量(可能的重複http://stackoverflow.com/questions/13091357/python-global-local -variables) –

回答

2

由於great被的first(),不second()範圍內定義。您需要將您的功能更改爲:

def first(): 
    great = 1 
    # code 
    second(great) 

def second(great): 
    if great == 1: 
     # code 
2

在Python中查找globals。這工作:

def first(): 
    global great 
    great = 1 
    print(great) 
    second() 

def second(): 
    if great == 1: 
    print ("awesome") 
    else: 
    print("God damn it!") 

first() 

在你原有的功能,great只是在first()當地範圍; second()不知道什麼/哪裏great是。全球(即可用於其他功能)製作great可解決您的問題。

編輯:上面代碼沒有工作,但也許是一個更好的方式來做事(每下面的建議),會是這樣:

great = 1 

def first(): 
    print(great) 
    second() 

def second(): 
    if great == 1: 
     print("awesome") 
    else: 
     print("God damn it!") 

或者更好的辦法是實際通過great(作爲參數)給每個函數的值。

+0

Downvoter:小心解釋爲什麼? – blacksite

+0

我投票支持你。我想知道爲什麼。 –

+0

您的代碼將無法使用。在讓他進入函數之前,你需要定義全局變量'great'。 'global'不會創建變量,但會從外部範圍獲取變量。 –

1

變量great在本地定義在first()。它在second()中不存在。您正在對不存在的變量進行相等性測試。

從一個函數的變量傳遞給其他...

def first(): 
    great = 1 
    print(great) 
    second(great) 

def second(great): 
    if great == 1: 
    print ("awesome") 
    else: 
    print("God damn it!") 

first()