1

I am trying to make an on/off switch for my program: (see after the ### for what I'm talking about)

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)

I get a continue not in loop error. Basically, I want to create an on or off switch after the program runs once. What do I fix?

asked Jan 14, 2013 at 18:18
0

1 Answer 1

11

You cannot use break and continue in a nested function. Use the return value of the function instead:

def switch():
 resp = raw_input("On or off? ")
 return resp == "on":
while True:
 # other code
 if not switch():
 break

Note that there is little point in defining your functions in the loop. Define them before the loop, as creating the function object takes some performance (albeit a small amount).

The switch() function needs no arguments (you didn't use them at all), and the continue is also not needed. If you didn't break out of the loop, it'll just continue from the top when you reach the end.

You only need continue if you want the loop to start at the top again skipping the rest of the code in the loop:

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.'
ThiefMaster
320k85 gold badges608 silver badges648 bronze badges
answered Jan 14, 2013 at 18:28
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.