T

TechIdea

Ecosystem

Pythonbeginner7 min read

Loops

Master for and while loops to repeat repetitive tasks efficiently without duplicating your code.

Learning Goals

1
Understand when to use for loops vs while loops in scripts.
2
Iterate over sequences of numbers using the range() function.
3
Control loop execution with break and continue statements.
4
Avoid infinite loop conditions by updating loop variables.

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

python
# 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

Required for Mastery

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?
Press Ctrl + C on your keyboard to force-terminate the execution.
What does the range() function return?
It returns a sequence of numbers, which is calculated lazily to save memory.

Continue Learning

Next steps after this lesson

Practice task

Write a program that uses a loop to calculate the sum of numbers from 1 to 10 (inclusive) and prints the final result.

Ready to take action?

Supercharge your career workflows!

Discover free online utilities to format data, build job applications, and automate your productivity routine with TechIdea.

Growth Newsletter

Get practical AI tools, SEO tips, and growth guides weekly.

Join creators, students, and businesses scaling with TechIdea.