簡體   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