Loops

Imagine you are listening your favourite song on loop. What does it mean? It means that the song is repeated until you stop it. The loop in python works the same way. So let’s dive right into it.

Python consists of 2 loops:

  • while Loop

  • for Loop

So loop should have following steps:

  1. Initialization (Start point)

  2. Condition (End point)

  3. Increment/Decrement (Update)

Let’s understand it with an if statement example.

  i = 0 # initialization
  if (i <= 5): # condition
    print(i)
    i=i+1 # increment

  >>> 0

In above code we are using if statement which is checking the condition either i is less than or equal to 5, if that condition comes out to be True then it will print the value of i and increment it by 1. And that’s it the execution will end there.

Now if we just replace the if keyword with while it will automatically become a while loop.

  i = 0 # initialization
  while (i <= 5): # condition
    print(i)
    i=i+1 # increment

  >>> 0
      1
      2
      4
      5

You can see that a while statement looks similar to an if statement. The difference is in how they behave. At the end of an if clause, the program execution continues after the if statement. But at the end of a while clause, the program execution jumps back to the start of the while statement. The while clause is often called the while loop or just the loop.

Note

If you forget any of the steps in while loop it will stuck in infinite loop, which we will cover later in this chapter.

while loop

You can make a block of code execute over and over again with a while statement. The code in a while clause will be executed as long as the while statement’s condition is True. In code, a while statement always consists of the following:

  • The while keyword

  • A condition (that is, an expression that evaluates to True or False)

  • A colon(:)

  • Starting on the next line, an indented block of code (called the while clause)

In the while loop, the condition is always checked at the start of each iteration (that is, each time the loop is executed). If the condition is True, then the clause is executed, and afterward, the condition is checked again. The first time the condition is found to be False, the while clause is skipped.

Let’s take an example of while loop which will print all numbers divisible by 5 starting from 10 to 20.

x = 10          # initialize `x` at 10 because our starting point is 10
while  x <= 20: # condition to check till `x` becomes 20
  if x % 5 ==0: # condition to check the number divisible by 5.
    print(x)
  x=x+1         # increment `x` by 1 (The short version of writing the same thing is x+=1) )
10
15
20

We can do the same thing in reverse order by changing the values like following code:

x = 20 # initialization
while x >= 10: # condition
  if x % 5 == 0:
    print(x)
  
  x-=1 # short version of x = x - 1 
20
15
10

Question

Now try out the same example for even numbers without if statement (in ascending and descending order).

An annoying while loop

So far so good, Now let’s see where something which makes while loop special i.e.- the condition. You should use while loop only when the condition is clear to you or the condition is explicitly mentioned. For example: If you have to keep asking for name to user until 'your name' is provided, shown in code below.

name = '' 
while name != 'your name':
    print('Please type your name')
    name = input() 
print('thank you!') 
Please type your name
Pranav
Please type your name
Vivek
Please type your name
aiadventures
Please type your name
your name
thank you!

First, the program sets the name variable to an empty string. This is so that the name != 'your name' condition will evaluate to True and the program execution will enter the while loop’s clause.

The code inside this clause asks the user to type their name, which is assigned to the name variable. Since this is the last line of the block, the execution moves back to the start of the while loop and reevaluates the condition. If the value in name is not equal to the string 'your name', then the condition is True, and the execution enters the while clause again.

But once the user types 'your name', the condition of the while loop will evaluate to False. Instead of re-entering the while loop’s clause, the program execution will skip past it and continues running the rest of the program.

If you never enter your name, then the while loop’s condition will never be False, and the program will just keep asking forever. Here, the input() call lets the user enter the right string to make the program move on. In other programs, the condition might never actually change, and that can be a problem.

So that was all about while loop. Now we will go ahead and learn for loop.

The while loop keeps looping while its condition is True (which is the reason for its name), but what if you want to execute a block of code only a certain number of times? You can do this with a for loop statement and the range() function. Hence it’s important to understand range() function first.

range() function

Some functions in python can be called with multiple arguments separated by a comma, and range() is one of them. range() function creates a sequence of integers, for that we have to mention following things:

  • start - The number from where sequence will start, its just like initialization from while loop.

  • stop - The number where the sequence will end, just like the condition of while loop to stop the loop.

  • step- The number which tells how much differene will be between next valud of the sequence, increment/decrement from while loop.

So if you remember we have mentioned in the start of the lesson those 3 properties of loops being used by for loop but in quite different way with the help of range() function.

The general syntax of range() function is :range(start, stop, step)

range(1, 5, 1)
range(1, 5)

The above code is not giving us the output because in Python 3 range() won’t display the complete sequence of integers. Hence we need for loop which will iterate over this sequence and display every element of the sequence until it ends. Let’s use the same sequence as above and create a for loop.

for i in range(1, 5, 1):
  print(i)
1
2
3
4

Just focus on the output for now, we will learn the syntax of for loop. If you look at the range() we have created the sequence from 1 to 5, but the output we are getting is from 1 to 4. It’s because the value of stop argument from the range() is exclusive from the sequence it means if we mention the stop number to be 5 it will stop at 4.

Note

Stop argument - Always remember it is excluded from the sequence. If you want the sequence from 0 to 10 both numbers included then your range() should be like range(0,11,1).

for i in range(1, 6):
  print(i)
1
2
3
4
5

Now what’s happenning in the above code is we are mentioning the start as 1 and stop as 6 (i.e.- the sequence will become 1, 2, 3, 4, 5), and we haven’t mentioned step so it automatically take it value as +1.

Note

Step argument - Step is to tell the difference between two consecutive numbers of the sequence. For example range(1,5,1) the step is +1 means increment. By default the value of step is +1 even if you didn’t provide it’s value it will be +1.

for i in range(6):
  print(i)
0
1
2
3
4
5

In above code we haven’t mentioned start and step argument both. The only value we have provided is stop. And it automatically starts from 0.

Note

Start argument - Start is to tell range from where the sequence should start. By default it’s value is 0, means if you don’t provide the start number it will automatically start from 0 as shown above.

Question

Now try to create a sequence from 5 to 1.(Hint - It has something to do with step).

for loop

Till now you have seen how we write for loop. Let’s break down it’s syntax.

In code, a for statement looks something like for i in range(5): and always includes the following:

  • The for keyword

  • A variable name

  • The in keyword

  • A call to the range() method with up to three integers passed to it

  • A colon(:)

  • Starting on the next line, an indented block of code (called the for clause)

The for loop will end where the sequence will end. That’s why range() function was so important.

Question

Now try creating a for loop which will print this sequence

10

20

30

40

50

As we have written a code for numbers divisible by 5 using while loop, we can do it using for loop too. As shown below:

for x in range(10, 21): # stop value will be 21 because 20 should get included in the sequence
  if x % 5 == 0:
    print(x) 
10
15
20

This example shows the similarity between for and while loop. If you know the end point or stopping point of the loop you can use both the loops.

But if you have to repeat something until some condition is False and you don’t know how many times the loop should repeat itself, then go with while loop. (Refer annoying while loop explained above).

Question

Now try out the for even numbers without if statement (in ascending and descending order) using for loop.

Till now you have seen that both the loops only gets over when it reaches its stopping point/condition.

But we can stop the loop before it reaches it’s stopping point/condition. by mentioning break statement.

break statement

break statement helps you stop any loop before it reaches it stop point. you just have to write break as shown below.

for i in  range(1,6):
  if i ==4:
    break
  print(i, end = ' ')
1 2 3 

continue statement

continue is opposite of break statement. continue statement will skip the loop to next value when the mentioned condition arises and go on until the loop reaches its stop point. Let’s understand it using code below.

for i in range(1,6):
  if i==3:
    continue
  print(i, end = ' ')
1 2 4 5 

Homework

Go on google and search about end argument from print() in python.

Types of loops:

  1. Nested Loops: Nested term in programming is used to show one thing is inside the other. Here we are using the term nested loop, it means one loop inside the other. for example while loop inside another while loop or for loop inside another for loop or for loop inside while loop or vice versa. Let’s understand it using few examples:

for i in range(3):
  for j in range(3):
    print(i,j)
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2

Now if you look closely you will observe that unless until the loop which is inside is gets over the outer loop won’t increment to next value. In simple word nexted loop acn be used to create possible combination of numbers.

Question

Now try the same thing with while loops.

  1. Infinite Loop: It is a loop which will go on until you explicitly break the loop. Usually infinte loop is created with while loop. Most of the time it could happen with you because you loop couldn’t reach it’s stop point. If it happens with you can just stop the execution by interrupting the runtime from google colab’s runtime section. This could be useful to you while creating your first project 3 Missionaries and 3 Cannibals.

i = 0
while i<=5:
  print(i)

Conclusion

You can execute code over and over again in a loop while a certain condition evaluates to True.

Questionaire

  1. How while loop is different than for loop?

  2. Define range() function in python and also its arguments.

  3. How to use break and continue statements in a loop?

  4. What loop is used to create infinite loop

  5. Can we use float value in step in range()?

Exercise

Try to solve the questions given in this link. And if you need any help understanding the questions feel free to seek for the mentor.

Assignment

We think it is enough Python concepts to develop a small game named 3 Missionaries and 3 Cannibals. Click on this link and start working on your skills you’ve learnt so far.

All the best!!!