繁体   English   中英

为什么说“水平”没有定义

[英]why does it say “level” is not defined

我正在尝试制作一个文本基础游戏,我想做一个关卡选择

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

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

说明:

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

解:

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

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

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

首先,level是函数levelselection的局部变量。

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

这样做 -

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

你忘了缩进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!")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM