[英]python while loop break
我正在嘗試對程序進行開/關切換:(請參閱###
之后的內容)
while 1:
str = raw_input("insert your word: ")
n = input("insert your scalar: ")
def string_times(str, n):
return n * str
print string_times(str, n)
###
def switch(on,off):
raw_input("On or off? ")
if switch == "on":
continue
if switch == "off":
break
switch(on,off)
我收到一個繼續未循環錯誤。 基本上,我想在程序運行一次之后創建一個開或關開關。 我該怎么解決?
您不能在嵌套函數中使用break
和continue
。 使用函數的返回值代替:
def switch():
resp = raw_input("On or off? ")
return resp == "on":
while True:
# other code
if not switch():
break
注意,在循環中定義函數沒有什么意義。 在創建循環對象之前定義它們,因為創建函數對象會帶來一些性能(盡管數量很少)。
switch()
函數不需要任何參數(您根本不需要使用它們),並且也不需要continue
。 如果您沒有打破循環,那么當您到達終點時,它只會從頂部繼續。
僅當您希望循環從頂部再次開始時,才需要continue
, 跳過循環中的其余代碼 :
count = 0
while True:
count += 1
print count
if loop % 2 == 0:
continue
print 'We did not continue and came here instead.'
if count >= 3:
break
print 'We did not break out of the loop.'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.