DEV Community

Romulo Gatto
Romulo Gatto

Posted on

Loops in Python (for and while)

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:

for element in sequence:
    # Perform actions on the element
Enter fullscreen mode Exit fullscreen mode

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

numbers = [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

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

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

for num in numbers:
    print(num)
Enter fullscreen mode Exit fullscreen mode

Output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

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:

range(5) 
Enter fullscreen mode Exit fullscreen mode

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:

while condition:
    # Perform actions until the condition becomes False
Enter fullscreen mode Exit fullscreen mode

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

num = 1

while num <= 5:
    print(num)
    num += 1
Enter fullscreen mode Exit fullscreen mode

Output:

1
2
3  
4  
5 
Enter fullscreen mode Exit fullscreen mode

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:

numbers = [1, 2, 3, 4]

for num in numbers:
    if num % 2 ==0:
        break

    print(num)
Enter fullscreen mode Exit fullscreen mode

Output:

1   
Enter fullscreen mode Exit fullscreen mode

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

i =0 

while i <10: 
   i +=i 

   if i >=6:    
       break 

print(i)        
Enter fullscreen mode Exit fullscreen mode

Output:

6              
Enter fullscreen mode Exit fullscreen mode

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:

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

for num in numbers:
    if num == 3:
        continue

    print(num)
Enter fullscreen mode Exit fullscreen mode

Output:

1   
2  
4  
5 
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)