似乎无法让我的'while True'循环保持循环

时间:2013-06-13 16:28:11

标签: python

我正在猜一个数字游戏,我有一个'while True'循环,我想继续循环,直到用户猜出正确的数字。现在我显示的数字是为了便于测试。不管我猜错了数字,我都会收到错误“'Nonetype'对象没有属性'猜猜'。”我很困惑为什么'while True'在第一次循环时没有错误但在此之后会出现错误。

Tracker.py

from Number import *

class Runner(object):
def __init__(self, start):
    self.start = start
    print Integer.__doc__
    print Integer.code

def play(self):
    next_guess = self.start

    while True:
        next_guess = next_guess.Guess()

        if next_guess == Integer.code:
            print "Good!"
            exit(0)

        else:
            print "Try again!"

Integer = Random_Integer()

Game = Runner(Integer)

Game.play()

Number.py

from random import randint

class Random_Integer(object):

"""Welcome to the guessing game! You have unlimited attempts
to guess the 3 random numbers, thats pretty much it."""

def __init__(self):
    self.code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
    self.prompt = '> '

def Guess(self):
    guess_code = raw_input(self.prompt)

谢谢!

1 个答案:

答案 0 :(得分:8)

您的.Guess()方法不会返回任何内容:

def Guess(self):
    guess_code = raw_input(self.prompt)

您需要在其中添加return语句:

def Guess(self):
    guess_code = raw_input(self.prompt)
    return guess_code

当函数没有显式的return语句时,它的返回值始终为None。因此,行:

next_guess = next_guess.Guess()

next_guess设置为None

但是,即使.Guess() 返回raw_input()结果,您现在已将next_guess替换为字符串结果,并在下一次迭代循环现在将失败,因为字符串对象没有.Guess()方法。

在将Integer实例作为参数传递给Runner()实例后,您还指向全局self.start值,并将其存储为self.start。不要依赖全局变量,你已经有class Runner(object): def __init__(self, start): self.start = start print start.__doc__ print start.code def play(self): while True: next_guess = self.start.Guess() if next_guess == self.start.code: print "Good!" exit(0) else: print "Try again!"

Integer

在上面的代码中,我们无需访问self.start全局,而是使用next_guessself.start.Guess()变量严格用于保存当前猜测,我们使用{{1}}代替。