PYTHON Tutorial



LOOPS IN PYTHON


πŸ”„ Loops in Python

Loops are used to execute a block of code repeatedly. Python provides two types of loops: for loop and while loop.

πŸ”Έ For Loop

The for loop is used to iterate over a sequence (like a list, tuple, string, or range).

# Using for loop to iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
  

πŸ”Έ While Loop

The while loop repeats as long as the given condition is True.

# Using while loop to print numbers
i = 1
while i <= 5:
    print(i)
    i += 1
  

πŸ”Έ Nested Loops

A loop inside another loop is called a nested loop. It’s often used to work with multi-dimensional data structures like lists of lists.

# Using a nested loop to iterate over a matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
    for item in row:
        print(item, end=" ")
    print()  # New line after each row
  

πŸ”Έ Break and Continue

You can control the flow of loops with break and continue statements:

# Using break to stop the loop
for i in range(10):
    if i == 5:
        break
    print(i)

# Using continue to skip the current iteration
for i in range(10):
    if i == 5:
        continue
    print(i)
  
πŸ’‘ Note: Always ensure that the condition in a while loop eventually becomes False, otherwise, the loop will run indefinitely.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review