2017-06-14 26 views
0

我在Windows 10設備上使用python 3.1,並且遇到了問題。分配聲明不能攜帶函數python 3.1

當我使用在另一個函數中定義的賦值時,賦值不起作用。我的問題在於很長的一段代碼,但是我做了一個更小的版本來幫助解釋發生的事情。

def test(): 
    """ takes input """ 
    f = input("1 or 2? ") 
    if f == 1: 
     t = "wow" 
    if f == 2: 
     t = "woah" 

def test2(t): 
    """ Uses input """ 
    print(t) 

def main(): 
    test() 
    test2(t) 

main() 
input("\n\nPress enter to exit") 

我不知道爲什麼程序在選擇輸入後不會使用賦值「t」。

我的目標是使用第一個函數的輸入來改變第二個函數的結果。當然,我的原始程序更復雜一點,簡單的打印功能,但這個演示是我知道搞亂我的程序。我的原始程序處理打開.txt文件,輸入是選擇打開哪個文件。

任何幫助將不勝感激。

+1

你的代碼有很多問題....'˚F== 1'是行不通的,因爲'F'是一個字符串,當'main()'中沒有定義時,如何將't'傳遞給'test2()' – depperm

+0

使用''global t''作爲函數塊的第一行(在doc之後) ,你想要訪問全局變量''t''。 (只有當你在函數''test()'')中改變它時才需要)或者你應該從測試中返回t''並且在main()''中把值賦給t。 – cmdLP

+0

在測試過程中,字符串部分是我的不好之處,但傳遞的是我想要解決的問題。你能解釋一下怎麼做嗎? – Collingpc

回答

1

你必須要想在test2將使用它返回「T」:

def test(): 
    """ takes input """ 
    f = input("1 or 2? ") 
    if f == '1': 
     t = "wow" 
    if f == '2': 
     t = "woah" 
    return t # This returns the value of t to main() 

def test2(t): 
    """ Uses input """ 
    print(t) 

def main(): 
    t = test() # This is where the returned value of t is stored 
    test2(t) # This is where the returned value of t is passed into test2() 

main() 
input("\n\nPress enter to exit") 
+0

不要忘記更新if語句也檢查字符串值。他們應該是'如果f =='1':'和'如果f =='2':' – DatHydroGuy

+0

我改變了這個和其他人指出的int/string問題,但它仍然給出相同的錯誤 – Collingpc

+0

感謝編輯@ DatHydroGuy。 – paperazzo79