[英]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.