Loops – for, while, iterators, generators python

By | December 5, 2018

Let’s learn about python loops in this blog.

In python, statements are executed sequentially. That means, first statement in a function is executed first, then second and so on.

Loops are useful when we want to run a block of code more than once. Looping is core feature of any programming language.

Python has following loops:

  • while loop
  • for loop
  • nested loops

while loop

A while loop in python executes block of statements till the given condition becomes false.

Remember, a block in python is written with indentation. There are no braces( { } ), like in many programming languages.

In while loop, the condition comes first. If condition is true, then code in while block is being executed.

When condition becomes false, execution of while loop ends. Line which is immediately after while loop, is next executed.

Let’s see one example:

In the code example above, we first declared variable x and assigned value 50 to it.

Next, we wrote a while loop that says, repeat statements within me till x becomes 0.

Inside the block, we decrease value of x by 1 during every iteration.

We used modulo operator for condition in if statement – one of the operators that we learnt in earlier blog. It helps us print the value of x, when it is decreased 5.

else with while

In Python, while loops can have an else statement. while loops have a condition to become true in order to enter into while block. 

We can write an else statement and a block of code to execute when the condition becomes false.

Here’s an example:

for loop

In Python, for loop is used to iterate over items in a sequence like list or string.

Let’s see an example:

else with for

Similar to while loop, we can use an else block with for loop. 

In case of while loop, the else block will execute only when the while condition becomes false.

In case of for loop, the else block will execute if for loop terminates normally, without any break statement execution.

Did you see the first line of above code ? It takes just one line of code to create a list with odd numbers between 1 to 10 😉

nested loops

We can write loop within loop, called nested loops. For variety of tasks, you will need to use this facility.

Let’ see how to write a nested loop in python with a fun example.

Summary

In this chapter, we learnt about loops in Python language. It is extremely important concept and we learnt it with cool and simple examples.

I hope you enjoyed it as much as I did. Do check the next blog here.

Keep learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *