✍️Introduction
In programming, we often need to repeat a task multiple times.
For example:
- Print numbers from 1 to 10
- Display all items in a list
Python uses loops to repeat a block of code.
In this article, you will learn:
- What loops are
- for loop
- while loop
- break and continue statements
What are Loops in Python?
Loops are used to execute a block of code repeatedly until a condition is satisfied.
Python mainly has two loops:
1. for loop
2. while loop
1️⃣ Python for Loop
The for loop is used to iterate over a sequence such as:
- list
- tuple
- string
- range
Syntax:
for variable in sequence:
statement
Example 1: Print numbers
for i in range(1, 6):
print(i)
Example 2: Loop through a list
languages = ["Python", "Java", "C"]
for lang in languages:
print(lang)
2️⃣ Python while Loop
The while loop runs as long as the condition is true.
Syntax:
while condition:
statement
Example:
i = 1
while i <= 5:
print(i)
i += 1
🔁 Difference Between for and while Loop
for Loop while Loop
Used when number. Used when condition
of iterations is known is unknown
Works with Works with
sequences condition
Simple & clean Needs manual control
3️⃣ break Statement
The break statement is used to stop the loop immediately.
Example:
for i in range(1, 10):
if i == 5:
break
print(i)
4️⃣ continue Statement
The continue statement skips the current iteration and continues with the next.
Example:
for i in range(1, 6):
if i == 3:
continue
print(i)
5️⃣ else with Loop
Python allows else with loops.
The else block runs when the loop finishes normally.
Example:
for i in range(3):
print(i)
else:
print("Loop completed")
❌ Common Loop Mistakes
- Infinite loop
- Forgetting to update variable
- Wrong indentation
Example of infinite loop:
while True:
print("Hello")
🎯 Why Loops are Important?
- Save time & code
- Used in data processing
- Important for exams & interviews
- Core concept of programming
Real-Life Example
password = "python123"
user_input = ""
while user_input != password:
user_input = input("Enter password: ")
print("Access granted")
Conclusion
Python loops help execute tasks efficiently and repeatedly.
Understanding for and while loops is essential for writing powerful programs.
Practice loops daily to master Python programming.
💬 Let’s Interact!
What will be the output?
for i in range(2, 5):
print(i)
Comment your answer 👇😊
📌 Related Articles:
Comments
Post a Comment