python - 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.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/

相关文章:

python - 如何在 matplotlib 中设置独立于刻度的条形宽度?

python - Atom 模块导入错误

security - Flask 文件处理 : Werkzeug Vs Flask-Uploads

python - uwsgi-nginx-flask : unable to load app 0 (mountpoint ='' ) (callable not found or import error)

python - Flask SSL 接收垃圾请求

Python3 - 缩短 Ubuntu 中主目录的路径

python - 如何对列表中的列表执行数学函数

python - 如何将错误陷阱循环回原始问题

python-2.7 - Opencv/numpy 问题 : "module compiled against API version X but this version of numpy is Y"

python - 如何将日志消息写入文件