簡體   English   中英

為什么我的python程序無法關閉

[英]Why does my python program not close

如果用戶未輸入yes,y,no或n,我希望此代碼停止循環該功能

go = True
def levelOne():
    print "You are in a room"
    print "There is a table, on the table there is a key"
    print "There is a door to the north"
    print "Use the key to open the door and escape?"
    userInput = raw_input()
    str(raw_input).lower()
    if userInput == "y" or userInput == "yes":
        print "Ok"
    elif userInput == "n" or userInput == "no":
        print "Fine, die then"
    else:
        go = False
While go == True:
    levelOne()

現在它無限循環,這是為什么呢?

問題在於levelOne並沒有修改全局變量go ,而是創建了一個具有相同名稱的新局部變量,該局部變量在函數返回時就消失了。*

解決方法是將global go添加到函數定義的頂部。

話雖這么說,使用全局變量幾乎永遠不是最好的解決方案。 為什么不僅僅擁有函數,例如, return Truereturn False ,那么您可以只while levelOne(): pass編寫?


我們在此注意一些注意事項:

  • (a)學習如何使用調試器,或(b)在每個中間步驟之后習慣於添加print語句,這是一個好主意。 當試圖找出問題出在哪里時,知道什么地方首先出了問題比試圖查看整個全局視圖並猜測可能出了什么問題要有用得多。
  • str(raw_input)試圖在raw_input函數本身上調用str ,這意味着它將為您提供類似於'<built-in function raw_input>' 您想在raw_input結果上調用它。 您將其存儲在名為userInput的變量中。
  • 無論如何,對raw_input結果的str都是無用的。 它保證是字符串,那么為什么要嘗試將其轉換為字符串呢?
  • str某事調用str ,然后對結果調用lower ,然后忽略其返回的任何內容,都無效。 這些函數都不修改其輸入,它們僅返回一個值,如果您想從中獲得任何好處,則必須將其用作參數或存儲在變量中。
  • if go == True:幾乎沒有用。 如果您只想檢查go是否正確,請使用if go: :。 如果您真的想確保它是單身常量True ,而不是其他的true,請使用is True (除其他原因外, 1 == True ,但1 is not True 。)

*在Python中,每當您分配一個名稱時,它始終會創建或重新綁定一個局部變量-除非您另行明確地告訴它,否則要使用global (或非nonlocal )語句,在這種情況下,它將創建或重新綁定一個全局(或非nonlocal )語句-local閉包)變量。

盡管有很多關於您的代碼的批評,但以下內容應按您的預期工作:

 def levelOne():
     print "You are in a room"
     print "There is a table, on the table there is a key"
     print "There is a door to the north"
     print "Use the key to open the door and escape?"
     userInput = raw_input()
     userInput = str(userInput).lower()
     if userInput in ("y", "yes"):
         print "Ok"
     elif userInput in ("n", "no"):
         print "Fine, die then"
     else:
         return False
     return True


 while levelOne():
     pass

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM