简体   繁体   中英

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: local variable 'html' referenced before assignment

I am getting this error. Can someone please suggest me what I am missing here, why I am getting the above error.

Fix the += if the variable was not used before and provide it to the function:

# 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) # 

Output:

<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>

or (less preferable) declare it global:

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>'''

Tip 1 :
Better string formatting using str.format() or f-strings / PEP-0498 / Literal String Interpolation

Tip 2 :
Adding to strings in a loop is wasteful - it constructs lots of intermediate strings that are thrown away. Use a list instead

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

Doku:

html+= someVal is same as html = html + someVal .

Having not been initialized before the variable html is undefined.

Since html is undefined you can't perform html + someVal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM