Loops in Python (for and while)
Published: 2024-02-12 15:10:03

# Loops in Python (for and while)

Loops are an essential concept in programming that allows us to execute a block of code repeatedly. In Python, we have two main types of loops: **for** and **while**. Both serve different purposes and understanding their differences will help you write more efficient and robust code.

## The **for** loop

The **for** loop is used to iterate over a sequence of elements such as lists, tuples, or strings. It allows us to perform a set of actions on each element in the sequence.

Here's the basic syntax for a **for** loop:

```python
for element in sequence:
    # Perform actions on the element
```

Let's say we have a list called `numbers` containing some integers:

```python
numbers = [1, 2, 3, 4, 5]
```

We can use a **for** loop to print each number in the list like this:

```python
numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print(num)
```

Output:
```
1
2
3
4
5
```

In this example, the variable `num` takes on the value of each element from the `numbers` list one by one as it goes through the loop.

Apart from sequences like lists and tuples, you can also use the range function with **for** loops to specify how many times you want your loop to run. For example:

```python 
range(5) 
```

This creates an iterable that generates numbers from 0 up to (but not including) 5.

## The **while** loop

The **while** loop is used when we want our code block to keep executing until a certain condition evaluates to False. Instead of iterating over sequences like with a for-loop; here we continuously execute our code block as long as the condition remains True.

The basic syntax for a **while** loop is:

```python
while condition:
    # Perform actions until the condition becomes False
```

To demonstrate, let's say we want to print numbers from 1 to 5 using a **while** loop:

```python
num = 1

while num <= 5:
    print(num)
    num += 1
```

Output:
```
1
2
3  
4  
5 
```

In this example, the variable `num` starts at 1, and the loop continues executing as long as `num` is less than or equal to 5. With each iteration, we increment the value of `num` by 1 using the `+=` operator. This ensures that the value of `num` eventually becomes greater than 5, causing the loop to terminate.

## Breaking out of loops

Sometimes you may need to exit a loop prematurely based on certain conditions. In Python, you can use the **break** statement to do just that.

Consider this example where we break out of a **for** loop when encountering an even number in our list:

```python
numbers = [1, 2, 3, 4]

for num in numbers:
    if num % 2 ==0:
        break
    
    print(num)
```

Output:
```
1   
```

Here's another example using a **while** loop with similar logic:

```python 
i =0 

while i <10: 
   i +=i 
    
   if i >=6:    
       break 
  
print(i)        
 ```

 Output: 
 
 ```
6              
 ```



## Skipping iterations with continue

On occasions when you want to skip iterations or certain parts of your code within a loop based on specific conditions; Python provides the **continue** keyword.

Let's say we have a **for** loop to print all numbers from 1 to 5, but we want to skip the number 3:

```python
numbers = [1, 2, 3, 4, 5]

for num in numbers:
    if num == 3:
        continue
    
    print(num)
```

Output:
```
1   
2  
4  
5 
```

As you can see, the number `3` is omitted from the output because when it encounters `num == 3`, it skips that iteration and continues with the next value.


## Conclusion

**For** and **while** loops are essential tools for any Python programmer. They allow us to repeat code blocks efficiently based on different conditions. By mastering these loop structures and learning how to break or continue iterations within them when needed; you will have more control over your programs and be able to solve complex problems with ease. So go ahead and start using loops in Python today!