1

我正在尝试编写一个简单的数字猜测程序。在这个特定的程序中,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()
4

2 回答 2

1

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

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

于 2013-06-21T10:28:04.983 回答
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
于 2013-06-21T10:17:44.837 回答