Comprehensive Practical Example

Example (without the break):

products = ['Apples', 'Bananas', 'Cherries']
prices = [100, 150, 200, 250, 300]  # Different price points

for product in products:  # Outer loop iterating over products
    print(f"Product: {product}")
    
    for price in prices:  # Inner loop iterating over prices
        if price > 200:  # Check when price exceeds 200
            print(f"Price {price} is high for {product}, but continuing.")
        
        print(f"Price: {price}")
    
    print(f"Finished checking prices for {product}\n")
Product: Apples
Price: 100
Price: 150
Price: 200
Price 250 is high for Apples, but continuing.
Price: 250
Price 300 is high for Apples, but continuing.
Price: 300
Finished checking prices for Apples

Product: Bananas
Price: 100
Price: 150
Price: 200
Price 250 is high for Bananas, but continuing.
Price: 250
Price 300 is high for Bananas, but continuing.
Price: 300
Finished checking prices for Bananas

Product: Cherries
Price: 100
Price: 150
Price: 200
Price 250 is high for Cherries, but continuing.
Price: 250
Price 300 is high for Cherries, but continuing.
Price: 300
Finished checking prices for Cherries

Order of Execution:

  1. For First Iteration & Second (Outer Loop for Apples, Bananas, cherries):
    • The first product is "Apples", and the outer loop starts by printing Product: Apples.
    • The inner loop starts iterating over the list of prices: 100, 150, 200, 250, 300.
      • For price = 100, the condition price > 200 is false, so it directly prints Price: 100.
      • For price = 150, the condition price > 200 is false, so it prints Price: 150.
      • For price = 200, the condition price > 200 is false, so it prints Price: 200.
      • For price = 250, the condition price > 200 is true, so it prints Price 250 is high for Apples, but continuing. and then prints Price: 250.
      • For price = 300, the condition price > 200 is true, so it prints Price 300 is high for Apples, but continuing. and then prints Price: 300.
    • After the inner loop finishes, the program prints Finished checking prices for Apples.

Order of Execution Summary:

  1. The outer loop starts with "Apples""Bananas", and "Cherries" in sequence.
  2. For each product, the inner loop iterates through all the prices.
  3. If a price exceeds 200 (250300), the message "Price {price} is high for {product}, but continuing." is printed, and the loop continues checking the next price (i.e., no break is involved).
  4. Each price is printed regardless of whether it's high or not.
  5. After the inner loop finishes for each product, the program prints Finished checking prices for {product} and moves to the next product.

NOTE 1 : Using the break before print, and after print

NOTE 2: Using the break before and after with else