- Python Features
- Python Installation
- PyCharm Configuration
- Python Variables
- Python Data Types
- Python If Else
- Python Loops
- Python Strings
- Python Lists
- Python Tuples
- Python List Vs Tuple
- Python Sets
- Python Dictionary
- Python Functions
- Python Built-in Functions
- Python Lambda Functions
- Python Files I/O
- Python Modules
- Python Exceptions
- Python Datetime
- Python List Comprehension
- Python Collection Module
- Python Sys Module
- Python Decorator
- Python Generators
- Python JSON
- Python OOPs Concepts
- Python Numpy Module
- Python Pandas Module
- Python Sqlite Module
Python Loops Tutorial
Introduction:
Loops are one of the most important concepts in Python. They allow you to execute a block of code repeatedly, which makes tasks like iterating through lists, performing calculations, or automating repetitive operations much easier
1). What Are Loops in Python?
A loop in Python is used to execute a set of statements multiple times until a certain condition is met. This helps avoid writing the same code over and over again. There are mainly two types of loops in Python:
- for loop
- while loop
2). Using the range() Function
The range() function is commonly used in loops to generate a sequence of numbers. It’s very useful when you want to repeat an action a specific number of times.
Syntax:
range(start, stop, step)
- start – the starting number (default is 0)
- stop – the number at which the range ends (not included)
- step – the difference between each number (default is 1)
Example 1:
Here, the loop runs 5 times, printing numbers from 0 to 4.
for i in range(5):
print(i)
Output :
0
1
2
3
4
Example 2:
for i in range(2, 10, 2):
print(i)
Output :
2
4
6
8
3). The for Loop
A for loop is used when you know how many times you want to execute a block of code. It’s great for iterating through sequences like lists, tuples, or strings.
# Example 1: Iterating through a list|
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
# Example 2: Iterating through a string
for letter in "Python":
print(letter)
Output:
P
y
t
h
o
n
4). Nested for Loops
A nested loop means having one loop inside another. This is often used for working with multidimensional data, like matrices or tables.
# Example:
for i in range(1, 4):
for j in range(1, 4):
print(f"i={i}, j={j}")
Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
i=3, j=1
i=3, j=2
i=3, j=3
Here, the inner loop runs completely every time the outer loop runs once
5). The while Loop
A while loop continues to run as long as a given condition is True. You use it when you don’t know how many times you need to repeat a block of code.
Example:
count = 0
while count < 5:
print("Count is:", count)
count += 1
Output:
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
If the condition never becomes False, the loop runs forever (an infinite loop). To avoid that, always make sure the condition changes within the loop.
6). The break Statement
The break statement is used to stop a loop immediately, even if the loop’s condition is still True.
# Example:
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
The loop stops when i equals 5, skipping the rest of the iterations.
7). The continue Statement
The continue statement is used to skip the rest of the code inside a loop for the current iteration and move to the next one
# Example:
for i in range(10):
if i % 2 == 0:
continue
print(i)
Output:
1
3
5
7
9
Here, every time i is even, the loop skips the print() statement and continues to the next iteration.
8). Combining break and continue
You can use both break and continue in the same loop to control its flow precisely.
# Example:
for i in range(10):
if i == 3:
continue
if i == 8:
break
print(i)
Output:
0
1
2
4
5
6
7
When i is 3, the continue statement skips that iteration. When i reaches 8, the break statement stops the loop entirely
9). Real-Life Example: Password Check
Here’s a simple example that uses both a while loop and break:
password = "python123"
attempts = 0
while attempts < 3:
guess = input("Enter password: ")
if guess == password:
print("Access granted!")
break
else:
print("Wrong password, try again.")
attempts += 1
else:
print("Too many attempts. Access denied.")
# This loop lets the user try three times before locking them out
10). Summary Table
| Concept | Description | Example |
| for loop | Runs a block of code a set number of times | for i in range(5): print(i) |
| while loop | Runs as long as a condition is true | while x < 10: |
| range() | Generates a sequence of numbers | range(1, 10, 2) |
| break | Stops the loop | if i == 5: break |
| continue | Skips current iteration | if i % 2 == 0: continue |
| Nested loop | A loop inside another | for i in range(3): for j in range(3): … |