Python Loops Explained for Beginners (for loop and while loop)
Python Loops Explained for Beginners (for loop and while loop)
Introduction
In the previous post, we learned about conditional statements. Now let’s learn how to repeat tasks using loops.
Loops help us execute the same block of code multiple times without writing it again.
---What is a Loop?
A loop is used to repeat a block of code until a condition is satisfied.
1️⃣ for Loop
The for loop is used when we know how many times the loop should run.
for i in range(5):
print(i)
Output:
0
1
2
3
4
Understanding range()
The range() function generates a sequence of numbers.
range(5) # 0 to 4
range(1, 6) # 1 to 5
range(1, 10, 2) # 1, 3, 5, 7, 9
for Loop with String
You can also use a for loop to iterate over a string.
name = "Python"
for ch in name:
print(ch)
2️⃣ while Loop
The while loop runs as long as the condition is True.
i = 1
while i <= 5:
print(i)
i = i + 1
Difference Between for and while Loop
- for loop → Used when the number of iterations is known
- while loop → Used when the condition decides repetition
Using break Statement
The break statement stops the loop immediately.
for i in range(10):
if i == 5:
break
print(i)
Using continue Statement
The continue statement skips the current iteration.
for i in range(5):
if i == 2:
continue
print(i)
Real-Life Example
Print numbers from 1 to 10 using a loop.
for i in range(1, 11):
print(i)
Common Beginner Mistakes
- Forgetting to update the condition in while loop
- Wrong indentation
- Infinite loop
What You Learned in This Post
- What loops are
- for loop and while loop
- break and continue
What’s Next?
Now that you understand loops, let’s learn about Python functions.
Next Post: Python Functions Explained for Beginners
---👋 About the Author
Ayush Gupta
MSc AI/ML Student | Machine Learning & Python Enthusiast
📧 Email:
aygupta9898@gmail.com
Comments
Post a Comment