在烧瓶中的数字猜谜游戏

时间:2017-10-12 16:37:20

标签: python python-2.7 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>

我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

我现在可以看到你的代码有两个问题。首先,您猜测的数字是以字符串形式出现的。为了将其与会话的猜测进行正确比较,您应该将其转换为整数,首先:int(request.form["guess"])

其次,在我看来,对于&#34;太低&#34;的比较运算符检查需要翻转。现在,它将返回&#34;太低&#34;当猜测的数字大于会话的数字时。你可能想要相反。

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

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