Loops β
π for Loops β
Basic for Loop β
python
# Loop through a sequence
for i in range(5):
print(i)
# Output: 0, 1, 2, 3, 4Loop through Lists β
python
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# Output: apple, banana, orangeLoop through Strings β
python
word = "Python"
for letter in word:
print(letter)
# Output: P, y, t, h, o, nLoop 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, 4User 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, 4continue 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: 15Example 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: 89Example 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: 3Example 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 β
forloops iterate over sequenceswhileloops continue until condition is falserange()generates number sequencesbreakexits loops earlycontinueskips current iteration- Nested loops create complex patterns
elseclause runs if loop completes normally
Continue to: Data Structures β