简体   繁体   中英

why does it say “level” is not defined

I am making trying to make a text base game and I want to make a level selection

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

over here, why does it say "level is not defined? and how can I fix it so the program works?

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

I would suggest you to read about python variables scope, this is a good source .

Explanation:

As level is initialized within the function levelselection you won't have access to the variable outside the function.

Solution:

1.You can fix this with defining level in a global scope.

2.Also, you can return level from the function as you did, but you will need to catch this return value, for example:

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

First of all , level is a local variable to your function levelselection .

After that you are returning level variable but not saving it to some other variable.

Do like this -

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

you forgot to indent the return level . So in your current code, the return doesn't belong to the levelselection() function.

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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