2017-05-28 71 views
1

我正在试图让一个文本基础的比赛,我想打一个级别选择为什么它说“级别”没有定义

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!") 
+1

你压痕关闭。另外,要使用函数的返回值,您需要*使用该值执行某些操作,例如将其分配给调用者范围内的变量。仅仅因为你的函数有一个名为'level'的局部变量,当你调用函数时,这个变量不会奇迹般地进入调用者的范围。 –

回答

0

我建议你阅读关于Python变量的作用域,这是一个很好的source

说明:

由于在函数levelselection中初始化了水平,所以您将无法访问该函数之外的变量。

解决方案:

1.You可以在全球范围内定义级别解决此问题。

2.Also,你可以从函数返回level像你一样,但你需要抓住这个返回值,例如:

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

首先,水平是一个局部变量您功能级别选择。

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

做这样的 -

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

你忘了缩进return level。因此,在您当前的代码中,回报不属于levelselection()函数。

试试这个:

def levelselection(): 
    level="" 
    while level != "1" and level != "2": 
    level = input("Please select a level to play: ") 
    return level 

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

'返回级别'几乎肯定是在OP的实际代码中缩进的,因为没有缩进,Stack Overflow初学者的工件不知道如何正确发布代码。如果缩进是问题,那么它们会有一个语法错误,它会阻止代码运行,而不是关于'level'未定义的运行时错误。 –

相关问题