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:
Explanation:
-
range(5)creates numbers from 0 to 4 -
iis the loop variable that changes each time -
The code inside the loop runs for each value of
i
Output:
The while Loop
The while loop repeats a block of code as long as a condition is True, Example:
Explanation:
-
The loop runs until
count < 5becomes False -
count += 1increases the value of count each time
Output:
Using break and continue
-
breakstops the loop immediately -
continueskips the current iteration and moves to the next
Example:
Output:
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.
0 Comments