2015-10-04 45 views
0

我的代碼:「引用賦值之前」錯誤條件語句

def sandwich(str, meat = 'ham', cheese = 'American'): 

    if sandwich(str, meat = None, cheese = None): 
     sandwich = str +' bread sandwich with turkey ' 
    else: 
     sandwich = str +' bread sandwich with ' + meat + ' and '+ cheese + ' cheese' 
    return sandwich 

我用一個定義參數嘗試。這沒有用。它給了我一個錯誤:

The local variable(sandwich) is being referenced before the assignment. 

請幫助!

+0

請粘貼問題的代碼在這裏,而不是在一些外部鏈接。 – Mureinik

+0

三明治(str,meat ='ham',cheese ='American'): 全球三明治 if sandwich(str,meat = None,cheese = None): sandwich = str +'bread sandwich sandwich with turkey' else : sandwich = str +'麪包三明治'+肉+'和'+奶酪+'奶酪' 返回三明治 –

+0

它也在描述中。鏈接是爲了這個問題。 –

回答

1

您正在再次調用該函數,並且您將變量命名爲與該函數相同的名稱。

糾正這兩個,和你結束了:

def sandwich(bread, meat='ham', cheese='american'): 
    if meat == None and cheese == None: 
     return '{} sandwich with turkey'.format(bread) 
    return '{} sandwich with {} and {} cheese'.format(bread, 
               meat, cheese) 
0

def sandwich(啓動功能定義。 sandwich將是該函數的名稱。

sandwich =開始分配。 sandwich將是變量的名稱。因爲您在函數體中執行此操作,變量將爲本地,並且Python假定您希望sandwich在函數的整個主體內引用該變量而不是函數

sandwich(str, meat = None, cheese = None)調用保存在局部變量sandwich中的函數。 (請記住,當您在函數體內編寫sandwich時,Python將假設您指的是本地變量。)但是沒有任何內容已分配給該變量,但是,因此您會收到提到的錯誤消息。

我想你想做的是檢查傳遞的函數參數。如果是這樣,Burhan's answer顯示你可能會這樣做。

0
def sandwich(bread, meat='ham', cheese='american'): 
    if meat == None and cheese == None: 
     return '{} bread sandwich with turkey'.format(bread) 
    return '{} bread sandwich with {} and {} cheese'.format(bread, meat, cheese) 

我不明白這是如何工作的。如果設定值'火腿'和'美國',第一個條件如何通過?這將永遠不會返回「{}麪包三明治土耳其」,因爲值被設置。