如何在HTML网页中运行简易Python输入测试代码?
Hey there! I get it—trying to get Python running in HTML can feel frustrating when tutorials don’t click. Let’s keep this straightforward: the easiest way to run your exact code (a = input("What is your favorite color?") print(a)) in a basic HTML page is using PyScript, a tool that lets you embed Python directly into your HTML without needing a separate server setup.
Here’s a step-by-step working example:
- Create a new HTML file (name it something like
color-test.html) - Paste this code into it:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Favorite Color Test</title> <!-- Load PyScript's required files --> <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> <script defer src="https://pyscript.net/latest/pyscript.js"></script> </head> <body> <h2>Python Input Test</h2> <!-- Your Python code goes inside the <py-script> tag --> <py-script> # This creates a visible input field on the page user_color = input("What is your favorite color? ") # The print statement outputs directly to the HTML page print(f"Your favorite color is: {user_color}") </py-script> </body> </html>
- Open the file in your browser (Chrome, Firefox, etc.)—that’s all you need to do!
What’s going on here?
- The
<link>and<script>tags load PyScript, which brings a full Python runtime directly to your browser. - The
<py-script>tag is where you write your Python code. Unlike regular Python, theinput()function here creates a visible text box on the page (instead of using the browser’s hidden console). When you type your color and press Enter, theprint()statement will display the result directly below the input box.
Why might your YouTube tutorials have failed?
Most tutorials for Python + HTML focus on server-side setups (like Flask or Django), where you run Python on a backend server and send results to the HTML page. That requires installing extra tools and configuring a server—way overkill for a simple input test. PyScript lets you skip all that complexity and run Python directly in the browser.
If you want an alternative, you could check out Brython (another browser-based Python runtime), but PyScript is more beginner-friendly and closely matches standard Python syntax.
内容的提问来源于stack exchange,提问作者sk.anu

