简体   繁体   中英

python while loop break

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?

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.'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM