为什么会说"等级"没有定义

时间:2017-05-28 14:26:01

标签: python python-3.x

我正在尝试制作一个基于文本的游戏,我想进行一个关卡选择

print ("You and your crew are pinned in the remains of a church on the top floor, with two wounded. Being fired at by German machine guns, matters will soon only get worse as you see German reinforcements on their way. Find a way to escape with your 9 man crew with minimal casualties.")
#Start up Menu
print ("Before you start the game ensure that you are playing in fullscreen to enhance your gaming experience")
print("")
print ("")
time.sleep(1)
print ("Menu")
print ('Instructions: In this game you will be given a series of paths. Using your best judgment you will choose the best path by using the "1" or "2" number keys, followed by pressing the "enter" button')
print ('If the wrong path is selected, there will be consequences of either death, or a lower final score.')
print ('Death will end the game, and you will be forced to start from the beginning of the level.')
time.sleep(1)
print ('If you will like to restart, press "r"')
print ('If you will like to quit, press "q"')
print ('If you  want to play level 1, press "a"')
print ('If you want to play level 2, press "s"')
print ('you cannot restart or quit at this time')
print ('')
print ('')
def levelselection():
    level=""
    while level != "1" and level != "2":
    level = input("Please select a level to play: ")
    return level

在这里,为什么说"等级没有定义?以及如何修复它以使程序有效?

levelselection()
if level == "1":
    print ("good job!")

3 个答案:

答案 0 :(得分:0)

我建议你阅读python变量范围,这是一个很好的source

<强>解释

在函数levelselection中初始化级别时,您将无法访问函数外部的变量。

<强>解决方案:

1.您可以通过在全局范围内定义级别来解决此问题。

2.另外,你可以像你一样从函数返回level,但你需要捕获这个返回值,例如:

level = levelselection()
if level == "1":
    print ("good job!")

答案 1 :(得分:0)

首先,level是函数级别选择的局部变量。

之后,您将返回级别变量,但不将其保存到其他变量。

这样做 -

levelselected = levelselection()
if levelselected == "1":
    print ("good job!")

答案 2 :(得分:0)

你忘了缩进public string Normalize(string input, string prefix, string suffix) { // Validation int length = input.Length; int startIndex = 0; if(input.StartsWith(prefix)) { startIndex = prefix.Length; length -= prefix.Length; } if (input.EndsWith (suffix)) { length -= suffix.Length; } return input.Substring(startIndex, length); } 。因此,在您当前的代码中,返回不属于return level函数。

试试这个:

levelselection()
相关问题