DEV Community

Akash Singh
Akash Singh

Posted on

Basic Python: 7. Python Loops

Loops allow you to repeat certain actions multiple times. The for loop and the while loop are commonly used in Python.

Table of Contents

  1. The for Loop
  2. The while Loop
  3. Loop Control Statements
  4. Nested Loops
  5. Looping Through Iterables

1. The for Loop

The for loop is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each element in the sequence.

Syntax:

for element in sequence:
    # Code block to be executed
Enter fullscreen mode Exit fullscreen mode

Example 1: Iterating Through a List

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
Enter fullscreen mode Exit fullscreen mode

Example 2: Using the range Function

for num in range(1, 6):  # Iterates from 1 to 5
    print(num)
Enter fullscreen mode Exit fullscreen mode

2. The while Loop

The while loop repeatedly executes a block of code as long as a given condition is true.

Syntax:

while condition:
    # Code block to be executed
Enter fullscreen mode Exit fullscreen mode

Example 3: Counting Down with while Loop

count = 5
while count > 0:
    print(count)
    count -= 1
Enter fullscreen mode Exit fullscreen mode

Example 4: Sum of Numbers Using while Loop

total = 0
num = 1
while num <= 10:
    total += num
    num += 1
print("Sum:", total)
Enter fullscreen mode Exit fullscreen mode

3. Loop Control Statements

Python provides loop control statements to modify the flow of loops.

  • 1. break Statement: Terminates the loop prematurely.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num == 3:
        break
    print(num)
Enter fullscreen mode Exit fullscreen mode
  • 2. continue Statement: Skips the remaining code and moves to the next iteration.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num == 3:
        continue
    print(num)
Enter fullscreen mode Exit fullscreen mode
  • 3. pass Statement: Acts as a placeholder for future code without affecting the loop's execution.
numbers = [2, 7, 3, 9, 5]

for num in numbers:
    if num % 2 == 0:
        print(f"{num} is even")
    else:
        pass  # Placeholder for future code

print("Loop finished")
Enter fullscreen mode Exit fullscreen mode

4. Nested Loops

You can nest loops within each other to handle more complex tasks.

rows = 3
cols = 3
for i in range(rows):
    for j in range(cols):
        print(f"({i}, {j})", end=' ')
    print()
Enter fullscreen mode Exit fullscreen mode

5. Looping Through Iterables

Python's built-in functions like enumerate(), zip(), and iteritems() make it easy to loop through and manipulate iterables.

# Using enumerate() to loop through a list with index and value
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
    print(f"Index: {index}, Fruit: {fruit}")
Enter fullscreen mode Exit fullscreen mode
# Using zip() to loop through multiple lists simultaneously
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 22]
for name, age in zip(names, ages):
    print(f"Name: {name}, Age: {age}")
Enter fullscreen mode Exit fullscreen mode
# Using items() to loop through key-value pairs in a dictionary
student_scores = {'Alice': 85, 'Bob': 70, 'Charlie': 92}
for name, score in student_scores.items():
    print(f"Name: {name}, Score: {score}")
Enter fullscreen mode Exit fullscreen mode

Top comments (0)