我正在制作一个策划者游戏,我刚开始并遇到了绊脚石。我需要允许用户选择游戏中的挂钩数量,然后允许用户猜测代码。我试图检查猜测的长度,并确保它与他们选择的钉子数相同。到目前为止,这是我的代码:
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()
即使我输入的猜测中的字母数量与我选择的挂钩数量相同而且我无法弄清楚原因,检查器()总是返回“错误的数字”。
谢谢!
答案 0 :(得分:1)
pegs()中的返回行应返回挂钩的数量,以便您可以保存该值并从程序的顶层再次使用它:
def pegs():
...
return numberOfPegs
让功能在返回之前打印您想要的内容。然后,在您的主程序中:
npegs = pegs()
checker(npegs) # send the number of pegs to the checker function
并适当地定义检查器:
def checker(pegs):
...
编辑添加:在Python中查看此explanation of scope。
答案 1 :(得分: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);