No Widget Added

Please add some widget in Offcanvs Sidebar

Shopping cart

shape
shape

Python Loops

loops in python, python loops, python in 2024, skills101.in, skills101

In Python, loops are used to repeatedly execute a block of code as long as a certain condition is met. Python supports two types of loops: for loops and while loops. Here’s an explanation of each type with simple examples.

1. For Loop

The for loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string). It executes a block of code once for each item in the sequence.

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 char in "hello":
    print(char)

Output:

h
e
l
l
o

Example 3: Using range()

for i in range(5):
    print(i)

Output:

0
1
2
3
4

2. While Loop

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

Example 4: Basic while loop

count = 0

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

Output:

0
1
2
3
4

Example 5: while loop with a condition

number = 10

while number > 0:
    print(number)
    number -= 2

Output:

10
8
6
4
2

3. Nested Loops

You can also nest loops inside each other.

Example 6: Nested for loop

for i in range(3):
    for j in range(2):
        print(f"i={i}, j={j}")

Output:

i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1

4. Control Statements

Python provides several control statements to control the flow of loops:

  • break: Exits the loop prematurely.
  • continue: Skips the rest of the code inside the loop for the current iteration and moves to the next iteration.
  • else: Executes a block of code once when the loop is finished (only if the loop is not terminated by a break statement).

Example 7: Using break

for i in range(10):
    if i == 5:
        break
    print(i)

Output:

0
1
2
3
4

Example 8: Using continue

for i in range(10):
    if i % 2 == 0:
        continue
    print(i)

Output:

1
3
5
7
9

Example 9: Using else with loops

for i in range(5):
    print(i)
else:
    print("Loop finished")

Output:

0
1
2
3
4
Loop finished

Summary

  • for loop: Used to iterate over a sequence.
  • while loop: Repeatedly executes a block of code as long as a condition is true.
  • Nested loops: Loops inside loops for more complex iterations.
  • Control statements: break, continue, and else to control the flow of loops.

Leave A Comment

Your email address will not be published. Required fields are marked *