Python Loops Tutorial

Loops are an essential concept in programming, and Python provides two main types of loops: for and while. I'll provide a brief tutorial on both types.

1. for Loop:

The for loop in Python is used for iterating over a sequence (that is either a list, tuple, dictionary, string, or range). Here's a basic syntax:

for variable in sequence:
    # code to be repeated

Example:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry

2. while Loop:

The while loop is used to repeatedly execute a block of code as long as a specified condition is true. Here's the syntax:

while condition:
    # code to be repeated

Example:

count = 0

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

Output:

0
1
2
3
4

3. Loop Control Statements:

a. break Statement:

The break statement is used to exit the loop prematurely.

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

Output:

0
1
2
3
4

b. continue Statement:

The continue statement is used to skip the rest of the code inside the loop for the current iteration and move to the next one.

for x in range(5):
    if x == 2:
        continue
    print(x)

Output:

0
1
3
4

4. Looping Through a Range:

The range() function is often used with loops to iterate a specific number of times.

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

Output:

0
1
2
3
4

5. Nested Loops:

You can use one or more loops inside another loop.

for i in range(3):
    for j in range(2):
        print(i, j)

Output:

0 0
0 1
1 0
1 1
2 0
2 1

These are the basics of loops in Python. They provide a powerful way to iterate over data and perform repetitive tasks in your programs.

Watch Now:- https://www.youtube.com/watch?v=as8vd_610HA