I'm trying to have HTML generate random background colors using Python. What I have so far is:
print "<body bgcolor='%s'>" % choice
what python code should follow?

Dani AI

Generated

Quick summary and modern fixes (for and anyone stumbling on this later): yes, picking a color server‑side is trivial (as indicated), but avoid the old HTML bgcolor attribute — use CSS (background-color) or an external stylesheet so the page is valid and accessible.

Two practical approaches (Python 3):

  • pick a named color from a list:

    import random
    
    named = ["teal", "coral", "lavender", "goldenrod", "slategray"]
    color = random.choice(named)
    html = f'<body style="background-color: {color};">'
    print(html)
  • generate a random hex color (far more variety):

    import random
    
    color = "#{:06x}".format(random.randint(0, 0xFFFFFF))
    html = f'<body style="background-color: {color};">'
    print(html)

If you want to use templates (answering ): IDLE is just an editor — it won't magically combine HTML and Python in the browser. For maintainable output use a templating engine (Jinja2 is a good general choice). Minimal example:

from jinja2 import Template

tpl = Template('<html><body style="background-color: {{ bg }};">Hello</body></html>')
print(tpl.render(bg=color))

Workflow notes and quick troubleshooting:

  • If serving via CGI or a web framework, remember proper response headers (or return the rendered template from your framework).
  • Ensure text remains readable on random backgrounds: compute luminance of the color and switch text to black/white accordingly.
  • For production, avoid inline styles — render a CSS variable or class from the template instead.
  • Test with a few contrasting colors and on mobile to catch edge cases.

These snippets are safe, concise ways to generate random backgrounds; use templates for larger pages and add a simple contrast check for accessibility.

Recommended Answers

All 7 Replies

I was also thinking of using a list of colors, like this:
bgcolor = ["red","blue","silver","green","yellow"]
but again, i'm unsure of how to use the random function with this list

see random.choice

Thanks that did it

Hi!I was wondering if I could know how to implement HTML along with python,
Do i simply use IDLE and enter (html+python)
OR do I have to call library packagesetc??
Thank You

Yes,I mean templating systems.
So how could I use IDLE to start typing HTML code like this
<table>
<%
for item in items:
%>
<tr>
<th>Name</th>
<td><%= item.name %></td>
</tr>
<%
%>
</table>

Which templatng engine should I be using,to generate HTML pages?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.