gpt4 book ai didi

python - Flask 中的猜数字游戏

转载 作者:行者123 更新时间:2023-12-01 02:32:00 24 4
gpt4 key购买 nike

我在 flask 中不断遇到与此代码相同的问题。我正在玩猜数字游戏,1-100,由于某种原因它总是响应“太低”。

from flask import Flask, render_template, session, request, redirect 
import random

app = Flask(__name__)
app.secret_key = 'thisIsSecret'

@app.route('/')
def index():
session['number'] = random.randrange(0,100)
print session['number']
return render_template("index.html")

@app.route('/guess', methods=['POST'])
def result():
if request.form['guess'] == session['number']:
answer = "Correct"
return render_template("index.html", answer=answer)
elif request.form['guess'] > session['number']:
answer = "Too Low"
return render_template("index.html", answer=answer)
else:
answer = "Too High"
return render_template("index.html", answer=answer)

app.run(debug=True)

我的 HTML 文件看起来像这样......

<html>
<head>
<title>Great Number Game</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>Welcome to the Great Number Game!</h1>
<h3>Think of a number 1 - 100...see if you can guess it right!</h3>
<p class="answer">{{ answer }}</p>
<form action='/guess' method='post'>
Guess: <input type='text' name='guess'>
<input type='submit' value='submit'>
</form>
</body>

我在这里做错了什么?

最佳答案

我现在发现您的代码有两处错误。首先,您猜测的数字以字符串形式输入。为了使其与 session 的猜测正确比较,您应该首先将其转换为整数:int(request.form["guess"])

其次,在我看来,“太低”检查的比较运算符需要翻转。现在,当猜测的数字大于 session 的数字时,它将返回“Too Low”。您可能想要相反的结果。

总之,您的第一个 elif 应该如下所示:

elif int(request.form['guess']) < session['number']:
answer = "Too Low"
return render_template("index.html", answer=answer)

关于python - Flask 中的猜数字游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46714773/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com