【问题标题】:Why is there unbound local error in this code?为什么此代码中存在未绑定的本地错误?
【发布时间】:2019-07-21 15:51:29
【问题描述】:
Traceback (most recent call last):
  File "script.py", line 30, in <module>
    print(censor_email_two(proprietary_terms))
  File "script.py", line 23, in censor_email_two
    result = ''.join(result.split(term_new[i]))
UnboundLocalError: local variable 'result' referenced before assignment
proprietary_terms = ["she", "personality matrix", "sense of self", "self-preservation", "learning algorithm", "her", "herself"]
def censor_email_two(term):
  email_two_new = email_two.split()
  term_new = ' '.join(str(term).split())
  for item in email_two_new: # to search EXACT wordings with a variable
    for i in range(len(term_new)):
      if item == term_new[i]: # to search EXACT wordings with a variable
        if i == 0:
          result = ''.join(email_two.split(term_new[i]))
        if i > 0 and i < len(term_new) - 1:
          result = ''.join(result.split(term_new[i]))
        if i == len(term_new) - 1:
          result = ''.join(result.split(term_new[i]))
          return result    
      else:
        continue

另外,这些代码行中是否有任何语法错误? email_two 已经被定义为全局变量

【问题讨论】:

  • 嗯,这个错误几乎是不言自明的......你在join中使用result,但它尚未定义......
  • 你当然需要用一些默认值初始化结果。
  • 但是我已经在if i == 0定义了?

标签: python python-3.x return


【解决方案1】:

您在分配结果时引用了结果(连接方法中的结果)。 python不知道join方法里面的结果是什么

result = ''.join(result.split(...)) ## error!

首先将结果分配给函数开头的result = ''

def censor_email_two(term):
    result = ''

【讨论】:

    猜你喜欢
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    • 2014-04-06
    相关资源
    最近更新 更多