I am creating a number guessing game to help myself learn how to use Google's App Engine. I store the current answer as a random number in the datastore. Each time the user guesses I want to pull the answer out in a GqlQuery and compare to the users guess. When I use the GqlQuery to pull the answer it returns 'None', and I don't know why or what to change to get the random number instead.
Here is where I store the answer -
class Answer(db.Model):
ans = db.IntegerProperty()
Here is how I store the random number when the user creates a new game -
thisanswer =(random.randint(1, 100))
answer = Answer(ans = thisanswer)
answer.put()
And I try to pull the answer out when the user submits a guess so I can compare to their guess like this-
q = db.GqlQuery("SELECT * FROM Answer")
q = q.fetch(1)
for p in q:
answer = p.ans
So when I try
if guess > an开发者_运维知识库swer:
msg = "Too high!"
elif guess < answer:
msg = "Too low!"
etc. I get the msg "Too high!" every time. So I changed the "Too high!" msg to this-
msg = "Too high! " + str(answer)
and what I get is-
"Too high! None"
Why is this code returning a value of 'None'? What do you recommend I change to get the random number that I expect to get. I have been following the App Engine Python docs for the datastore but obviously I am overlooking something. Thanks for any insight on this.
It's possible there are no answers in the database. Verify it with:
msg = "Total answers in database: " + str(Answer.all().count())
A more elegant way of getting the first answer in the database would be:
answer = Answer.all().get()
# or (equivalent)
answer = db.GqlQuery("SELECT * FROM Answer").get()
if answer is not None:
number = answer.ans
else:
number = None
精彩评论