设置功能的默认值

时间:2018-04-20 09:29:12

标签: python

我创建了解析JSON文件的子任务问题的函数。根据故障单的数量,此功能有时会返回1,有时会返回更多行,有时甚至不返回任何内容。

 def subtask():
     for issue in data['issues']:
      for subtask in issue['fields']['subtasks']:
        if subtask['fields']['summary'] != 'Workspace created':
          x = subtask['fields']['summary']
     return x

接下来,我将此变量的输出传递给if块:它只检查函数输出是否包含"工作区创建"以外的单词。

x=subtask()


for issue in data['issues']:
 if len(issue['fields']['subtasks']) == 0 or x != "Workspace created":
      print issue['key']
      print issue['fields']['description']

subtasks()函数返回任何值时,它按预期工作,但如果函数没有输出则失败:

UnboundLocalError: local variable 'x' referenced before assignment

如果没有输出,如何指定函数的默认值? 例如x=""我试过了:

def subtask(x=None):
 for issue in data['issues']:
  for subtask in issue['fields']['subtasks']:
    if subtask['fields']['summary'] != 'Workspace created':
      x = subtask['fields']['summary']
    if x is None:
       x = "test"
 return x

但它返回" test"对于带有和不带汇总字段的票证。

2 个答案:

答案 0 :(得分:1)

问题在于,如果条件if subtask['fields']['summary'] != 'Workspace created':永远不会成立,则x未初始化,因此错误local variable 'x' referenced before assignment

你的第二个代码的问题是类似的,如果“first if - condition”不成立,那么“second if-condition”就没有x

要解决此问题,请在进入循环之前设置x=None

def subtask():
 x = None # set default value of x here
 for issue in data['issues']:
  for subtask in issue['fields']['subtasks']:
    if subtask['fields']['summary'] != 'Workspace created':
      x = subtask['fields']['summary']
 return x

答案 1 :(得分:0)

我简化代码(删除功能)

data = response.json()
    for issue in data['issues']:
       for subtask in issue['fields']['subtasks']:
           s = subtask['fields']['summary']
       if len(issue['fields']['subtasks']) == 0 or subtask['fields']['summary'] != "Workspace created":
           print issue['fields']['description']
           print issue['key']