用python制作一个网页案例
时间: 2023-10-10 18:09:45 浏览: 68
好的,我们可以使用 Flask 框架来制作一个简单的网页。下面是一个实现了一个简单的计算器功能的示例代码:
```python
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def calculator():
if request.method == 'POST':
num1 = float(request.form['num1'])
num2 = float(request.form['num2'])
operator = request.form['operator']
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
result = num1 / num2
else:
result = 'Invalid operator'
return render_template('calculator.html', result=result)
else:
return render_template('calculator.html')
if __name__ == '__main__':
app.run(debug=True)
```
我们需要在同级目录下创建一个 templates 文件夹,里面放置一个名为 calculator.html 的模板文件,用于渲染我们的网页界面。这里只展示了部分 HTML 代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Calculator</title>
</head>
<body>
<h1>Calculator</h1>
<form method="post">
<input type="number" name="num1" required>
<select name="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="number" name="num2" required>
<input type="submit" value="Calculate">
</form>
{% if result %}
<p>Result: {{ result }}</p>
{% endif %}
</body>
</html>
```
运行程序后,访问 http://127.0.0.1:5000/ 即可看到我们的网页。在输入框中输入两个数字并选择一个运算符,点击 Calculate 按钮即可计算出结果并显示在网页上。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)