[SOLVED] Outputting HTML unordered list python

Issue

I’m attempting to write a function with python that will take an list of strings that I have defined and display them as a single string that is and HTML unordered list of said strings. So far my code is:

def pizzatoppings(self):
    toppings = ['mushrooms', 'peppers', 'pepparoni', 'steak', 'walnuts', 'goat cheese', 'eggplant', 'garlic sauce'];
    for s in toppings:
        ul += "<li>"+str(s)+"</li>"
        ul += "</ul>"
        return ul

When I attempt to run this however I get no traceback and nothing happens. Does anyone know why this is happening? I know this is probably a trivial question but I’ve searched for answers and cannot find a solution. Thanks!

Solution

You could do something like that:

def print_ul(elements):
    print("<ul>")
    for s in elements:
        ul = "<li>" + str(s) + "</li>"
        print(ul)
    print("</ul>")

toppings = ['mushrooms', 'peppers', 'pepparoni', 'steak', 'walnuts', 'goat cheese', 'eggplant', 'garlic sauce'];
print_ul(toppings)

There were some problems with your original code:

  • you did not call the function, so no wonder it didn’t do anything
  • even if you did, the function did not actually print anything, it just returned some values
  • the function didn’t really take arguments, so it was not re-usable at all

A better (IMO) solution would be to have a function generating the HTML code, and printing the result:

def ulify(elements):
    string = "<ul>\n"
    for s in elements:
        string += "<li>" + str(s) + "</li>\n"
    string += "</ul>"
    return string

print(ulify(['thing', 'other_thing']))

You can also read about list comprehensions. It would make working with lists simpler:

def ulify(elements):
    string = "<ul>\n"
    string += "\n".join(["<li>" + str(s) + "</li>" for s in elements])
    string += "\n</ul>"
    return string
    

Answered By – Ealhad

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *