Loops are used to execute a block of code multiple times. Python provides two main types of loops:
for loop (used for iterating over sequences like lists, tuples, strings, etc.)while loop (executes until a condition becomes False)Loops help in reducing redundancy and improving code efficiency.
for LoopThe for loop is used when you want to iterate over a sequence like a list, tuple, dictionary, string, or range.
for variable in sequence:
# Code to executefruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)apple
banana
cherryrange() in for LoopThe range() function generates a sequence of numbers.
for i in range(5): # Generates numbers 0 to 4
print(i)0
1
2
3
4range(start, stop, step)for i in range(1, 10, 2): # Start from 1, stop at 10, step by 2
print(i)1
3
5
7
9for char in "Python":
print(char)P
y
t
h
o
nwhile LoopThe while loop runs as long as the condition is True.
while condition:
# Code to executecount = 1
while count <= 5:
print(count)
count += 1 # Increment count1
2
3
4
5break and continue)break (Stops the Loop)for num in range(1, 10):
if num == 5:
break # Stops when num is 5
print(num)1
2
3
4continue (Skips Current Iteration)for num in range(1, 6):
if num == 3:
continue # Skips number 3
print(num)1
2
4
5else with LoopsPython allows else with loops, which executes if the loop completes normally (i.e., without break).
else with forfor i in range(1, 4):
print(i)
else:
print("Loop completed successfully!")1
2
3
Loop completed successfully!else with whilex = 1
while x < 4:
print(x)
x += 1
else:
print("Loop completed!")1
2
3
Loop completed!A loop inside another loop.
for i in range(1, 3):
for j in range(1, 4):
print(f"i={i}, j={j}")i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3An infinite loop runs forever if the stopping condition is never met.
while True:
print("This will run forever!") # Press Ctrl+C to stoptotal = 0
for num in range(1, 6):
total += num
print("Sum:", total)Sum: 15for loops iterate over sequences like lists, strings, and ranges.while loops run as long as the condition is True.break stops the loop, and continue skips an iteration.else runs when loops finish normally.
Nested loops allow loops inside loops.
Sign in to join the discussion and post comments.
Sign inPython for Web Development
Python for Web Development is a comprehensive tutorial series covering the fundamentals of building web applications using Flask and Django. From setting up a project to working with databases, authentication, REST APIs, and deployment on cloud platforms, this series provides a solid foundation for developing secure and scalable web applications.
Object-Oriented Programming (OOP) in Python
Learn the fundamentals of Object-Oriented Programming (OOP) in Python, including classes, objects, inheritance, polymorphism, encapsulation, and more. Understand how OOP enhances code reusability, scalability, and organization.