2013-06-26 146 views
2
in file1.py 
def foo(): 
    sum=2+4 
    return sum 

def bar(sum): 
    print sum 

in file2.py 
import file1 
file1.foo() 
file1.bar(sum) 

當我這樣做,我得到這樣的如何返回值從一個函數調用到另一個

NameError: name 'sum' is not defined 

一個錯誤怎麼返回值調用函數... 幫助我!

+0

file1.bar(file1.foo())? – Kevin

+0

sum是一個內置函數,在蟒蛇中,我建議不要用它來命名變量。而是使用sum_或別的東西。 –

回答

1

將從file1.foo返回的值存儲在變量中。在函數內部創建的變量只對該函數是本地的,並且不能在該函數之外訪問。

import file1 
ret = file1.foo() #strore it's return value in `ret` 
file1.bar(ret)  #now pass `ret` to this function 

,不使用sum作爲變量名,因爲它會掩蓋內置函數sum

+0

非常感謝你.... – user2470026

相關問題