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: