Python Loops: for, while, and nested loops

Python Loops: for, while, and nested loops

Python Loops: for, while, and nested loops

Loops are used in Python to execute a block of code repeatedly. There are two main types of loops: for and while. Additionally, you can have nested loops, where one loop is inside another.

1. The for Loop

Use the for loop to iterate over a sequence (such as a list or a string).


# Example
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)
        

2. The while Loop

Use the while loop to repeatedly execute a block of code as long as a condition is true.


# Example
count = 0
while count < 5:
    print(count)
    count += 1
        

3. Nested Loops

You can have one loop inside another. This is known as nested loops.


# Example
for i in range(3):
    for j in range(2):
        print(i, j)
        
Python Loops: for, while, and nested loops Python Loops: for, while, and nested loops Reviewed by Naveen Gupta on 1:17 AM Rating: 5

No comments:

Theme images by mammamaart. Powered by Blogger.