Junior — Middle
How can three random elements be displayed on a single web page in an application?
sobes.tech AI
Answer from AI
To display three random items on a web application page in Python, you can use a web framework like Flask and the Jinja2 templating engine.
Example:
from flask import Flask, render_template_string
import random
app = Flask(__name__)
items = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5']
@app.route('/')
def index():
random_items = random.sample(items, 3) # Select 3 random items without repetition
template = '''
<html>
<body>
<h1>Random Items</h1>
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</body>
</html>
'''
return render_template_string(template, items=random_items)
if __name__ == '__main__':
app.run(debug=True)
This code runs a simple web server that, when accessed at the main page, selects three random elements from the list and displays them as a list on the page.