🐍 Python Course 10: More Loops

🎯 Learning Objectives

After completing this section, you will understand:

⚡ Prerequisites

  • Understanding of while loops
  • Basic arithmetic operations
  • Knowledge of conditional statements

1. For Loops with Range

The range() function generates a sequence of numbers, perfect for for loops:

# Basic range with one argument (stop) for i in range(5): # 0 to 4 print(i) # Range with start and stop for i in range(1, 6): # 1 to 5 print(i) # Range with start, stop, and step for i in range(0, 10, 2): # Even numbers 0 to 8 print(i)

Range Function Parameters

2. Loop Control Statements

Python provides statements to control loop execution:

Break Statement

# Exit loop when condition met for i in range(1, 11): if i == 5: break print(i) # Prints 1, 2, 3, 4

Continue Statement

# Skip current iteration for i in range(1, 6): if i == 3: continue print(i) # Prints 1, 2, 4, 5

3. Nested Loops

You can place one loop inside another to handle more complex patterns:

# Multiplication table for i in range(1, 4): for j in range(1, 4): print(f"{i} x {j} = {i*j}") print() # Empty line between rows # Output: # 1 x 1 = 1 # 1 x 2 = 2 # 1 x 3 = 3 # # 2 x 1 = 2 # 2 x 2 = 4 # 2 x 3 = 6 # # 3 x 1 = 3 # 3 x 2 = 6 # 3 x 3 = 9

Tips for nested loops:

4. Common Loop Patterns

Here are some common patterns you'll use with loops:

Pattern Printing

# Print a triangle for i in range(5): print('*' * (i + 1)) # Output: # * # ** # *** # **** # *****

Running Total

# Calculate sum of numbers total = 0 for i in range(1, 6): total += i print(f"Sum: {total}") # Sum: 15
📝 Exercise: Number Pyramid

Create a number pyramid pattern:

rows = 5 for i in range(1, rows + 1): for j in range(1, i + 1): print(j, end=' ') print() # Output: # 1 # 1 2 # 1 2 3 # 1 2 3 4 # 1 2 3 4 5
📝 Exercise: Prime Numbers

Find prime numbers in a range:

def is_prime(n): if n < 2: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True # Print prime numbers from 1 to 20 for num in range(1, 21): if is_prime(num): print(num, end=' ') # Output: 2 3 5 7 11 13 17 19

🎉 Summary

You've learned about:

This completes Part 2 of the Python course!