Python Set For and While Loops


In Python, loops are used to repeat a block of code multiple times.

There are two main types of loops in Python - for loops and while loops.

for Loops

The for loop is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string).

numbers = {1,2,3,4,5,6}
for num in numbers:
  print(num)

Iterating over a range of numbers

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

This loop will print numbers from 0 to 4.


while Loops

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

Using a while loop

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

This loop will print numbers from 0 to 4. The loop continues until count is no longer less than 5.


Using break and continue

break - Exits the loop.
continue - Skips the rest of the code inside the loop for the current iteration and moves to the next iteration

Using break in a loop

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

This loop will print numbers from 0 to 4 and then exit.

Using continue in a loop

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

This loop will print only odd numbers from 1 to 9.

Combining Loops with Conditional Statements

You can combine loops with if statements to perform more complex operations.

Nested loops with conditionals

for i in range(3):
    for j in range(3):
        if i == j:
            print(f"i and j are both {i}")

This nested loop will print when the values of i and j are equal.

Loops are fundamental to programming, and mastering them will allow you to handle repetitive tasks efficiently.