Loops
Master for and while loops to repeat repetitive tasks efficiently without duplicating your code.
Learning Goals
The Core Concept
Loops are used to repeat a block of code multiple times. Python offers two main types of loops: for loops and while loops.
A for loop is ideal when you know beforehand how many times you want to iterate (such as looping over a list of names or a range of numbers). A while loop continues to run as long as a specified condition remains True. It is crucial to make sure that the condition eventually becomes False, otherwise your program will get stuck in an infinite loop.
Visual guide
Python automation process
A simple original diagram to connect the lesson idea with real project flow.
Code & Implementation
# 1. For loop over a range
print("Counting to 3:")
for number in range(1, 4):
print(number)
# 2. While loop with a counter
print("
Countdown:")
count = 3
while count > 0:
print(count)
count = count - 1
print("Liftoff!")Expected Output
Counting to 3: 1 2 3 Countdown: 3 2 1 Liftoff!
Sum of Numbers Loop
Hands-on practice task
The Challenge
Write a program that uses a loop to calculate the sum of numbers from 1 to 10 (inclusive) and prints the final result.
Helpful Hints
- •Create a variable total_sum = 0 before the loop.
- •Use a for loop: for num in range(1, 11).
- •Add num to total_sum in each iteration: total_sum += num.
Quick Knowledge Check
How do I stop an infinite loop in terminal?
What does the range() function return?
Continue Learning
Next steps after this lesson
Write a program that uses a loop to calculate the sum of numbers from 1 to 10 (inclusive) and prints the final result.
Supercharge your career workflows!
Discover free online utilities to format data, build job applications, and automate your productivity routine with TechIdea.