search

Home  >  Q&A  >  body text

Grammar - In Python, can the break and continue statements only be used with if?

In Python, can the break and continue statements only be used with if?
The picture below is from Liao Xuefeng’s website

我想大声告诉你我想大声告诉你2757 days ago1667

reply all(2)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-05-18 11:00:06

    No, continue and break must be used in for, while and other loops. Break and continue cannot be used in a separate if statement.
    Give me an example

    # Example 1
    for a in [1, 2, 3, 4]:
        if (a == 1):
            continue
        else:
            print(a)
    # 2
    # 3
    # 4
    
    # Example 2
    for a in [1, 2, 3, 4]:
        print(a)
        continue
        

    Continue and break cannot be used for separate if

    # Example 3
    if True:
        continue
    # SyntaxError: 'continue' not properly in loop
        
    

    reply
    0
  • 某草草

    某草草2017-05-18 11:00:06

    Of course not, break and continue are used to break out of the loop

    reply
    0
  • Cancelreply