Control Flow - Loops
Learn how to repeat actions in your code using for and while loops
Learning Objectives
- Understand why we use loops
- Write 'while' loops for conditional repetition
- Write 'for' loops to iterate over sequences
- Use 'break' and 'continue' to control loop execution
- Understand the 'range()' function
Repeating Actions
If you want to print “Hello” 10 times, you could write print("Hello") ten times, but that’s inefficient. Instead, we use loops.
Python provides two main types of loops: for loops and while loops.
The while Loop
A while loop repeats a block of code as long as a condition is True.
|
|
The for Loop
A for loop is used to iterate over a sequence (like a list, a string, or a range of numbers).
Using range()
The range() function generates a sequence of numbers.
|
|
range(5)gives numbers: 0, 1, 2, 3, 4.range(1, 6)gives numbers: 1, 2, 3, 4, 5.range(0, 10, 2)gives even numbers: 0, 2, 4, 6, 8 (step of 2).
Loop Control: break and continue
Sometimes you need to exit a loop early or skip an iteration.
break: Exits the loop immediately.continue: Skips the rest of the current block and starts the next iteration.
|
|
Interactive Practice
Try writing a loop that calculates the sum of all numbers from 1 to 100.
Quiz
Complete this quiz with a minimum score of 80% to mark Day 5 as complete.
Discussion
Have questions or want to discuss this lesson? Join the conversation below!