2015-10-04 63 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) 

我不明白这是如何工作的。如果设定值'火腿'和'美国',第一个条件如何通过?这将永远不会返回“{}面包三明治土耳其”,因为值被设置。