![](/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.