HOME
ABOUT

Control Flow: Loops

Control Flow: Loops

for Loop

# Iterate through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Using range()
for i in range(5):
    print(i)  # Prints 0 to 4

while Loop

count = 0
while count < 5:
    print(count)
    count += 1

Loop Control

# break statement
for num in range(10):
    if num == 5:
        break
    print(num)

# continue statement
for num in range(10):
    if num % 2 == 0:
        continue
    print(num)

Nested Loops

for i in range(3):
    for j in range(2):
        print(f"i={i}, j={j}")

else with Loops

for num in range(5):
    print(num)
else:
    print("Loop completed successfully")

Related Articles

  • Introduction to Python
  • Setting Up Python Environment
  • Python Syntax Basics
  • Variables and Data Types
  • Operators
  • Input and Output
  • Control Flow: Conditionals
  • Control Flow: Loops
  • Functions
  • Lists and Tuples
  • Dictionaries and Sets
  • String Manipulation
  • How to execute SQL queries (Select, Update, Insert, Delete) effectively using Python?