![](/img/trans.png)
[英]UnboundLocalError: local variable 'truebomb' referenced before assignment
[英]UnboundLocalError: local variable 'html' referenced before assignment
html += '''
<table style="width:100%">
<tr align="center">
<th style="width:10%">Metrics</th>
'''
def get_bus_metrics (met,name):
for i in met:
html += '<th>' + str(i) + '</th>'
html += '''</tr>'''
html += '''<tr><th>''' + name +'''</th>'''
get_bus_metrics (g1,'R')
UnboundLocalError:赋值前引用的局部变量'html'
我收到了这个错误。 有人可以建议我在这里缺少什么,为什么我得到上述错误。
修复+=
如果之前没有使用变量并将其提供给函数:
# fix here - no += unless you decleared html as some string beforehand
html = '''
<table style="width:100%">
<tr align="center">
<th style="width:10%">Metrics</th>
'''
# fix here - else not known
def get_bus_metrics (met,name,html):
for i in met:
html += '<th>' + str(i) + '</th>'
html += '''</tr>'''
html += '''<tr><th>''' + name +'''</th>'''
return html
html = get_bus_metrics (range(1,5),'R',html) # provide as parameter: cleaner
print(html) #
输出:
<table style="width:100%">
<tr align="center">
<th style="width:10%">Metrics</th>
<th>1</th><th>2</th><th>3</th><th>4</th></tr><tr><th>R</th>
或(不太可取)将其声明为全局:
def get_bus_metrics (met,name,html):
# don't use globals, they are _evil_ - if you need to _modify_ smth
# from global scope, you need to announce this in the function
# reading works without if decleard earlier then the function,
# changing it needs this line:
global html
for i in met:
html += '<th>' + str(i) + '</th>'
html += '''</tr>'''
html += '''<tr><th>''' + name +'''</th>'''
提示1 :
使用str.format()或f-strings / PEP-0498 / Literal String Interpolation更好地进行字符串格式化
提示2 :
在循环中添加字符串是浪费的 - 它构造了许多被抛弃的中间字符串。 请改用列表
def get_bus_metrics (met,name,html):
t = []
for i in met:
t.append('<th>{}</th>'.format(i)) # using format(..)
t.append(f'</tr><tr><th>{name}</th>') # using string interpol
return html+''.join(t) # faster, less wasted intermediate strings
数独:
html+= someVal
与html = html + someVal
。
在变量html
未定义之前尚未初始化。
由于html
未定义,因此无法执行html + someVal
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.