Python猜测我的号码(反向猜数)UnboundLocalError

时间:2013-06-21 10:09:36

标签: python python-2.7

我正在尝试编写一个简单的数字猜测程序。在这个特定的程序中,python猜测用户正在考虑的数字,而不是相反。

我的代码返回UnboundLoalError。

此外,这一切似乎太长而且繁琐。我怎样才能缩短它?

谢谢。

# Guesses a number

from random import randint
number = ""

def numberGuesser():
    while True:
        print "Think of a number between 1 and 50"
        raw_input("Hit a key when ready")
        number = randint(1,50)
        answer = raw_input("Is your number: %d?. y/n> " % number)
        if answer == 'y':
            print "Great!"
            raw_input("Hit a key to exit.")
        elif answer == 'n':
            greater_or_smaller()
        else:
            print "Please type y or n"



def greater_or_smaller():
    while True:
        greater_or_smaller = raw_input("Is\
 your number greater or smaller than %d? g/s> " % number)
        if greater_or_smaller == 'g':
            number = randint(number, 50)
            answer = raw_input("Is your number %d? y/n> " % number)
            if answer == 'y':
                print "Hooray!"
            elif answer == 'n':
                greater_or_smaller()

        elif greater_or_smaller == 's':
            number = randint(1, number)
            answer = raw_input("Is your number %d? y/n> " % number)
            if answer == 'y':
                print "Hooray!"
            elif answer == 'n':
                greater_or_smaller()


numberGuesser()

2 个答案:

答案 0 :(得分:1)

这:

        if greater_or_smaller == 'g':
            number = randint(number, 50)
            answer = raw_input("Is your number %d? y/n> " % number)
            if answer == 'y':
                print "Hooray!"
            elif answer == 'n':
                greater_or_smaller()

        elif greater_or_smaller == 's':
            number = randint(1, number)
            answer = raw_input("Is your number %d? y/n> " % number)
            if answer == 'y':
                print "Hooray!"
            elif answer == 'n':
                greater_or_smaller()

可能是:

        if greater_or_smaller in ['g','s']:
            number = randint(number, 50) if greater_or_smaller == 'g' else randint(1, number)
            answer = raw_input("Is your number %d? y/n> " % number)
            if answer == 'y':
                print "Hooray!"
            elif answer == 'n':
                greater_or_smaller()

此外,您应该编写一个小函数来处理与用户的交互,以确保答案包含在预期答案列表中。

类似的东西:

def get_input(prompt_text, valid_options):
    x = raw_input(prompt_text)
    while x not in valid_options:
        print x, "is not a valid value. Expected are :", valid_options
    return x

答案 1 :(得分:1)

您收到此错误是因为函数greater_or_smallernumber调用中使用变量raw_input,然后稍后分配给它。将global number放在函数顶部,错误就会消失。 (但是请听听你在这里得到的其他建议)。

说明:要分配或修改全局变量,必须先将其声明为全局变量。 (您可以使用全局/非局部变量而不将其声明为全局变量,只要您不在函数中的任何位置分配它。)