[英]How to 'break' if statement in Python
這只是我代碼的一小部分
def menu():
choices = ["Create a Scenario", "Load a Database", "Quit"]
m1 = eg.choicebox("What would you like to do?", "Greenfly Model Menu", choices)
if m1 == "Load a Scenario":
dbless = eg.enterbox("What is the name of your database?")
if dbless is None:
menu()
db_name = dbless + ".db"
check = os.path.isfile(db_name)
如果變量dbless最終為None,則代碼最終將按預期運行menu()函數。 但是,其余代碼之一執行完畢,該功能的其余部分最終運行。 無論如何都要這樣做,以便其余功能無法運行。
使用return
語句而不是考慮不帶循環的函數內部的break
。
您可以包括while
循環,以便在輸入不為None之前,它會要求輸入:
while dbless is None:
menu()
else: #you can remove the else and unindent the next two lines, but I'm used to do it that way
db_name = dbless + ".db"
check = os.path.isfile(db_name)
我在這里看到的問題是,它將無限期地詢問輸入內容。 如果您對此有疑問,可以在此期間添加類似attempt
,但我認為並非如此。 另外,我不確定該代碼是否真的會有效,因為再次調用該函數...無論如何,請嘗試一下。
您不應在循環外使用break語句。 因此,您需要使用return語句。 您可以通過兩種方式做到這一點。
if dbless is None:
menu()
return
要么
if dbless is None:
return menu()
您可以嘗試一下,這將與您的邏輯保持一致:
def menu():
choices = ["Create a Scenario", "Load a Database", "Quit"]
m1 = eg.choicebox("What would you like to do?", "Greenfly Model Menu", choices)
if m1 == "Load a Scenario":
dbless = eg.enterbox("What is the name of your database?")
flag=0
while flag<1:
if dbless is None:
menu()
break
db_name = dbless + ".db"
check = os.path.isfile(db_name)
flag+=1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.