[英]breaking while loop with function?
我正在嘗試制作一個具有if / elif語句的函數,並且我希望if中斷while循環。該函數用於文本冒險游戲,是/否的問題。 到目前為止,這是我想出的。
def yn(x, f, g):
if (x) == 'y':
print (f)
break
elif (x) == 'n'
print (g)
name = raw_input('What is your name, adventurer? ')
print 'Nice to meet you, '+name+'. Are you ready for your adventure?'
while True:
ready = raw_input('y/n ')
yn(ready, 'Good, let\'s start our adventure!',
'That is a real shame.. Maybe next time')
現在我不確定我是否正確使用該功能,但是當我嘗試一下時,它說我不能中斷該功能。 因此,如果有人可以幫助我解決該問題,並且如果函數和調用函數本身的格式錯誤,則可以幫助我,將不勝感激。
您可以例外處理:
class AdventureDone(Exception): pass
def yn(x, f, g):
if x == 'y':
print(f)
elif x == 'n':
print(g)
raise AdventureDone
name = raw_input('What is your name, adventurer? ')
print 'Nice to meet you, '+name+'. Are you ready for your adventure?'
try:
while True:
ready = raw_input('y/n ')
yn(ready, "Good, let's start our adventure!",
'That is a real shame.. Maybe next time')
except AdventureDone:
pass
# or print "Goodbye." if you want
這樣一遍又一遍地循環while
循環,但是在yn()
函數內部,引發了一個異常,該異常打破了循環。 為了不打印回溯,必須捕獲並處理異常。
您需要打破循環本身內的while循環,而不是脫離另一個函數。
類似以下內容可能更接近您想要的:
def yn(x, f, g):
if (x) == 'y':
print (f)
return False
elif (x) == 'n':
print (g)
return True
name = raw_input('What is your name, adventurer? ')
print 'Nice to meet you, '+name+'. Are you ready for your adventure?'
while True:
ready = raw_input('y/n: ')
if (yn(ready, 'Good, let\'s start our adventure!', 'That is a real shame.. Maybe next time')):
break
您需要將函數內部的中斷更改為return,並且需要使用else
語句,以防用戶未向您提供正確的輸入。 最后,您需要將while loop
的調用轉換為if語句。
如果玩家輸入了所需的命令,這將使您打破while語句,否則,它將再次詢問。 我還更新了yn
函數,以允許用戶同時使用大小寫字符以及yes和no。
def yn(input, yes, no):
input = input.lower()
if input == 'y' or input == 'yes':
print (yes)
return 1
elif input == 'n' or input == 'no':
print (no)
return 2
else:
return 0
name = raw_input('What is your name, adventurer? ')
print 'Nice to meet you, %s. Are you ready for your adventure?' % name
while True:
ready = raw_input('y/n ')
if yn(ready, 'Good, let\'s start our adventure!',
'That is a real shame.. Maybe next time') > 0:
break
這背后的想法很簡單。 yn
函數具有三種狀態。 用戶回答是,否或無效。 如果用戶響應為“是”或“否”,則該函數將返回1(是)和2(否)。 並且,如果用戶沒有提供有效的輸入,例如空格,它將返回0。
在while True:
循環中,我們使用if statement
包裝yn('....','....')函數,該if statement
檢查yn
函數是否返回大於0的數字。因為yn
將返回0。用戶為我們提供了有效輸入,有效輸入為1或2。
一旦收到來自yn
的有效響應,我們將調用break,這將終止while loop
,並完成了操作。
一種方法是讓yn
返回一個布爾值,然后將其用於中斷循環。 否則,函數內的break
無法脫離調用函數中的循環。
def yn(x, f, g):
if (x) == 'y':
print (f)
return True
elif (x) == 'n'
print (g)
return False
name = raw_input('What is your name, adventurer? ')
print 'Nice to meet you, '+name+'. Are you ready for your adventure?'
done = False
while not done:
ready = raw_input('y/n ')
done = yn(ready, 'Good, let\'s start our adventure!', 'That is a real shame.. Maybe next time')
使用break,即使不滿足循環結束的條件,也可以退出循環。 您無法中斷,因為'if / elif'不是循環,它只是一個條件語句。
a = True
def b():
if input("") == "Quit":
global a
a == False
else:
pass
while a == True:
print('Solution')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.