Python 烧瓶中的数字猜谜游戏
我在flask中的代码一直遇到同样的问题。我在玩数字猜谜游戏,1-100,出于某种原因,它总是回答“太低”Python 烧瓶中的数字猜谜游戏,python,python-2.7,flask,Python,Python 2.7,Flask,我在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
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>
大数游戏
欢迎来到大数字游戏!
想一个数字1-100…看看你是否能猜对!
{{answer}
猜测:
我做错了什么 我现在可以看出您的代码有两处错误。首先,你猜到的数字是以字符串的形式出现的。为了正确地将其与会话的猜测进行比较,您应该将其转换为整数,首先:
int(request.form[“guess”])
其次,在我看来,“过低”检查的比较运算符需要翻转。现在,当猜测的数字大于会话的数字时,它将返回“过低”。你可能想要相反的结果
总之,您的第一个elif
应该如下所示:
elif int(request.form['guess']) < session['number']:
answer = "Too Low"
return render_template("index.html", answer=answer)
elif int(request.form['guess'])