0

我正在制作一个策划游戏,我刚刚开始并遇到了一个绊脚石。我需要允许用户选择游戏中的钉子数量,然后让用户猜测代码。我正在尝试检查猜​​测的长度,并确保它与他们选择的钉子数量相同。到目前为止,这是我的代码:

def pegs():
    numberOfPegs = input("Please enter the number of pegs in the game between 3 and 8 ")
    if numberOfPegs < 3:
        return ("Make sure you enter a number between 3 and 8")
    elif numberOfPegs > 8:
        return ("Make sure you enter a number between 3 and 8")
    else:
        return ("Thank you, you are playing with", numberOfPegs, "pegs")



def checker():

    guess = raw_input("Please enter your guess as letters ")
    if len(guess) != pegs:
        print "Wrong number!"
    else:
        return 1

print pegs()
print "\n"
print checker()

并且 checker() 总是返回“错误的数字”,即使我输入的猜测中的字母数量与我选择的钉子的数量相同,我不知道为什么。

谢谢!

4

2 回答 2

1

pegs() 中的返回行应该返回 pegs 的数量,以便您可以保存该值并从程序的顶层再次使用它:

def pegs():
    ...
    return numberOfPegs

在返回之前让函数打印您想要的内容。然后,在您的主程序中:

npegs = pegs()
checker(npegs)   # send the number of pegs to the checker function

并适当地定义检查器:

def checker(pegs):
    ...

编辑添加:查看Python中范围的这个解释。

于 2013-11-10T10:46:29.723 回答
0
def get_pegs():
    numberOfPegs = input("Please enter the number of pegs in the game between 3 and 8 ")
    if numberOfPegs < 3:
        print ("Make sure you enter a number between 3 and 8");
        return 0;
    elif numberOfPegs > 8:
        print ("Make sure you enter a number between 3 and 8");
        return 0;
    else:
        print ("Thank you, you are playing with ", numberOfPegs, " pegs");
        return numberOfPegs;

def checker(pegs):

    guess = raw_input("Please enter your guess as letters ")
    if len(guess) != pegs:
        print "Wrong number!"
    else:
        print "Number ok";    #for debugging, remove later
        return 1

pegs =  get_pegs();
print "\n"
result = checker(pegs);
于 2013-11-10T10:56:09.070 回答