Skip to content

Python loop

  • by

A loop in Python is a control flow statement that allows you to execute a block of code repeatedly. There are two types of loops in Python: for loop and while loop.

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

for item in sequence:
    # Code block to be executed for each item

Example:

fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
    print(fruit)

while loop: The while loop is used to repeatedly execute a block of code as long as a specified condition is true.

while condition:
    # Code block to be executed as long as the condition is true

Example:

count = 1
while count <= 5:
    print(count)
    count += 1

Both types of loops are powerful constructs that help you automate repetitive tasks or process data iteratively. Be careful when using loops to ensure they don’t result in infinite loops, where the condition is never met, causing the loop to run indefinitely. Always include a way to break out of the loop if needed.

Python loop examples

Here are some more Python loop examples to illustrate various use cases:

1. Looping through a list and calculating the sum of elements:

numbers = [1, 2, 3, 4, 5]
sum_result = 0

for num in numbers:
    sum_result += num

print("Sum of elements:", sum_result)

2. Looping through a string and printing each character:

message = "Hello, World!"

for char in message:
    print(char)

3. Looping through a range of numbers and printing them:

for i in range(1, 6):
    print(i)

4. Using a while loop to find the first power of 2 greater than 100:

power_of_two = 1

while power_of_two <= 100:
    power_of_two *= 2

print("First power of 2 greater than 100:", power_of_two)

5. Using continue to skip odd numbers and print only even numbers:

for num in range(1, 11):
    if num % 2 != 0:
        continue
    print(num)

6. Using break to exit the loop when a certain condition is met:

fruits = ['apple', 'banana', 'orange', 'pear', 'grape']

for fruit in fruits:
    if fruit == 'orange':
        break
    print(fruit)

Output:

Python loop

These are just a few examples to showcase the flexibility and utility of loops in Python. You can use loops in various combinations and with different data structures to accomplish a wide range of tasks.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading