python - 似乎无法让我的 'while True' 循环继续循环

标签 python

我正在做一个猜数字游戏,我有一个“while True”循环,我想一直循环直到用户猜出正确的数字。现在我显示了数字以便于测试。不管我是否猜对了数字,我都会收到错误消息“'Nonetype' 对象没有属性'Guess'。” 我很困惑为什么'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()

数字.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)

谢谢!

最佳答案

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

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

您需要在此处添加一个return 语句:

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

当一个函数没有明确的返回语句时,它的返回值总是None。因此,行:

next_guess = next_guess.Guess()

next_guess 设置为 None

但是,即使 .Guess() 确实 返回它的 raw_input() 结果,您现在已经替换了 next_guess 与一个字符串结果,你通过循环的下一次迭代现在将失败,因为字符串对象没有 .Guess() 方法。

在将它作为参数传递给您的 Runner() 实例并将其存储为 self 之后,您还到处引用全局 Integer 值。从那里开始。不要依赖全局变量,你已经有了 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.startnext_guess 变量严格用于保存当前猜测,我们使用 self.start.Guess() 代替。

关于python - 似乎无法让我的 'while True' 循环继续循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17092307/

相关文章:

python - Django 百分比表单域

python - django admin.autodiscover() urls 文件上的导入顺序

python - Django : Programmatically add Groups on User save

python - 将组总计添加到 Pandas 中的数据框的最佳方法

Python 的 win32api 只打印到默认打印机

python - 将python日期格式(%Y)转换为java(yyyy)

尝试使用用户定义的类时出现 Python NameError

python - 交换从树移动指针中随机选择的两个节点的角色的算法

python - Scrapy 获取所有子项/忽略 <br>?

python - 合并具有相同名称的数据框列,但不对列进行排序