python - 如何在 HTML 页面上呈现 Python 猜数字游戏
问题描述
我刚刚从一本名为 Automate the Boring Stuff With Python 的书中学会了猜数字游戏(代码如下)。我让它使用终端工作,但我想知道如何设置它以在 html 页面上呈现。理想情况下,我现在想使用 Flask 并在本地渲染 html 页面。
import random
correct = random.randint(1,20)
print('I am thinking of a number between 1 and 20.')
for guessesTaken in range(1,6):
print('Take a guess.')
guess = int(input())
if guess < correct:
print('Your number is too low')
elif guess > correct:
print('Your number is too high')
else:
break
if guess == correct:
print('Good work! You got the number in '+ str(guessesTaken)+ ' guesses')
else:
print('Nope. The number I was thinking of was ' + str(correct))
解决方案
创建一个文件夹,其中包含 1 个名为 app.py 的文件和 1 个名为 templates 的文件夹,其中包含 a.html
1) 应用程序.py
from flask import Flask
from flask import request
from flask import render_template
import random
correct = random.randint(1,20)
count=0
app = Flask(__name__)
@app.route('/new')
def my_form():
return render_template("a.html") # this should be the name of your html file
@app.route('/new', methods=['POST'])
def my_form_post():
global correct
global count
msg = ''
print(count)
if count<6:
count+=1
text1 = request.form['text1']
text1 = int(text1)
if text1 < correct:
msg = 'Your number is too low'
return render_template("a.html", msg=msg)
elif text1 > correct:
msg = 'Your number is too high'
return render_template("a.html", msg=msg)
else:
if text1 == correct:
msg = 'Good work! You got the number in '+ str(count)+ ' guesses'
count = 0
correct = random.randint(1,20)
return render_template("a.html", msg=msg)
else:
num = 'Nope. The number I was thinking of was ' + str(correct)
correct = random.randint(1,20)
msg = ''
count=0
return render_template("a.html", num=num)
if __name__ == '__main__':
app.run(debug=True)
2)一个.html
<!DOCTYPE html>
<html lang="en">
<body>
<h1>I am thinking of a number between 1 and 20.</h1>
<form action="/new" method="POST">
<input type="text" name="text1">
<input type="submit" name="my-form" value="Check !">
</form>
<h1>{{ msg }}</h1>
<h1>{{ num }}</h1>
</body>
</html>
推荐阅读
- calendar - 如何通过 URL 在 Google 日历中包含来宾和创建新活动的通知
- css - 如何停止`-webkit-background-clip:text`使文本变薄?
- javascript - 如何比较数字并返回最高值?
- linker - 如何在 STM32/platformio/arduino 上保留一个 Flash 内存扇区
- game-maker-studio-2 - GMS2 参数总是返回 undefined
- python - 如何从终止的 multiprocessing.Process 中抑制 stderr?
- python - 根据 Python 中类型对象的字符串表示检查对象的类型
- java - 如何在java中两次处理输入流
- android - Jetpack Navigation:任何片段都应该能够导航到任何片段
- node.js - 与副本集的猫鼬连接不起作用