Skip to content

Loops ​

πŸ”„ for Loops ​

Basic for Loop ​

python
# Loop through a sequence
for i in range(5):
    print(i)
# Output: 0, 1, 2, 3, 4

Loop through Lists ​

python
fruits = ["apple", "banana", "orange"]

for fruit in fruits:
    print(fruit)
# Output: apple, banana, orange

Loop through Strings ​

python
word = "Python"

for letter in word:
    print(letter)
# Output: P, y, t, h, o, n

Loop with Index ​

python
fruits = ["apple", "banana", "orange"]

for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")
# Output: 0: apple, 1: banana, 2: orange

πŸ”’ range() Function ​

python
# range(stop)
for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

# range(start, stop)
for i in range(2, 7):
    print(i)  # 2, 3, 4, 5, 6

# range(start, stop, step)
for i in range(0, 10, 2):
    print(i)  # 0, 2, 4, 6, 8

πŸ” while Loops ​

Basic while Loop ​

python
count = 0

while count < 5:
    print(count)
    count += 1
# Output: 0, 1, 2, 3, 4

User Input Loop ​

python
password = ""

while password != "secret":
    password = input("Enter password: ")
    
print("Access granted!")

πŸ›‘ Loop Control Statements ​

break Statement ​

python
# Exit the loop early
for i in range(10):
    if i == 5:
        break
    print(i)
# Output: 0, 1, 2, 3, 4

continue Statement ​

python
# Skip current iteration
for i in range(10):
    if i % 2 == 0:
        continue
    print(i)
# Output: 1, 3, 5, 7, 9

πŸ”„ Nested Loops ​

python
# Multiplication table
for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i} Γ— {j} = {i * j}")
    print()  # Empty line between tables

🎯 Loop with else ​

python
# else runs if loop completes without break
for i in range(5):
    if i == 10:
        break
    print(i)
else:
    print("Loop completed normally")

πŸš€ Practice Examples ​

Example 1: Sum of Numbers ​

python
numbers = [1, 2, 3, 4, 5]
total = 0

for number in numbers:
    total += number
    
print(f"Sum: {total}")  # Sum: 15

Example 2: Find Maximum ​

python
numbers = [45, 23, 78, 12, 89, 34]
maximum = numbers[0]

for number in numbers:
    if number > maximum:
        maximum = number
        
print(f"Maximum: {maximum}")  # Maximum: 89

Example 3: Count Vowels ​

python
text = "Hello World"
vowels = "aeiouAEIOU"
count = 0

for char in text:
    if char in vowels:
        count += 1
        
print(f"Vowels: {count}")  # Vowels: 3

Example 4: Guessing Game ​

python
import random

secret_number = random.randint(1, 100)
attempts = 0

while True:
    guess = int(input("Guess the number (1-100): "))
    attempts += 1
    
    if guess == secret_number:
        print(f"Correct! You guessed it in {attempts} attempts")
        break
    elif guess < secret_number:
        print("Too low!")
    else:
        print("Too high!")

πŸ“ List Comprehensions Preview ​

python
# Instead of this:
squares = []
for x in range(10):
    squares.append(x**2)

# You can write this:
squares = [x**2 for x in range(10)]

🎯 Key Takeaways ​

  • for loops iterate over sequences
  • while loops continue until condition is false
  • range() generates number sequences
  • break exits loops early
  • continue skips current iteration
  • Nested loops create complex patterns
  • else clause runs if loop completes normally

Continue to: Data Structures β†’

Released under the MIT License.