Skip to main content

Posts

Showing posts with the label for loop with else

For Loop with else in Python

  Learning Sections          show For Loop with Else in Python In Python, a `for` loop can have an `else` clause that executes when the loop completes normally (i.e., not interrupted by a `break` statement). Here are some examples: 1. Basic Example In this example, the `else` block executes because the loop completes without encountering a `break` statement. # A list of numbers numbers = [1, 2, 3, 4, 5] # Iterate through the list for number in numbers : print ( number ) else : print ( "Loop completed without break" ) # Output: # 1 # 2 # 3 # 4 # 5 # Loop completed without break 2. With Break In this example, the `else` block does not execute because the loop is terminated by a `break` statement. # A list of numbers numbers = [1, 2, 3, 4, 5] # Iterate through the list for number in numbers : if number == 3: break print ( number ) else : print ( "Loop com...