我正在尝试为我的程序设置开/关开关: (请参阅 ### 之后我在说什么)
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.'
