Python Loops

Hey friends 👋 welcome back, In the last lesson, we learned about conditional statements, Today, we are going to learn about loops, which allow our programs to repeat actions multiple times automatically, Loops are very useful for tasks that need to be done repeatedly.

The for Loop

The for loop is used to repeat a block of code a specific number of times, Example:

for i in range(5): print("Hello,", i)

Explanation:

  • range(5) creates numbers from 0 to 4

  • i is the loop variable that changes each time

  • The code inside the loop runs for each value of i
    Output:

Hello, 0 Hello, 1 Hello, 2 Hello, 3 Hello, 4

The while Loop

The while loop repeats a block of code as long as a condition is True, Example:

count = 0 while count < 5: print("Count is", count) count += 1

Explanation:

  • The loop runs until count < 5 becomes False

  • count += 1 increases the value of count each time
    Output:

Count is 0 Count is 1 Count is 2 Count is 3 Count is 4

Using break and continue

  • break stops the loop immediately

  • continue skips the current iteration and moves to the next
    Example:

for i in range(5): if i == 3: break print(i)

Output:

0 1 2

Practice Time

Create a Python file called loops.py and try these exercises, 1, Use a for loop to print numbers from 1 to 10, 2, Use a while loop to print numbers from 5 to 1, 3, Use a loop to print all even numbers between 1 and 20, 4, Use a for loop with break and continue to skip number 3

Great job, You just learned how to repeat actions in Python using loops, In the next lesson, we will explore Python Functions, where we will learn how to organize code into reusable blocks, We will soon be launching our YouTube channel, where we are going to post step-by-step video tutorials on Python and other tech skills, These videos will make learning easier and more visual, helping beginners follow along confidently.