Mark As Completed Discussion

In this lesson, we will learn about loops and iterations in programming, with a focus on the following key points,

  1. What are iterations in programming?
  2. Working with loops and related concepts in Python.

For the Javascript version of this lesson, please click here.

During programming, you may encounter situations when you want to repeat a block of code a certain number of times. Repeating the same code, again and again, is slow, untidy, and is prone to errors. These kinds of problems in programming are dealt with concepts called loops and iterations. This automates the process of applying a similar operation to a collection of elements, or statements within a program.

One example where loops are extremely helpful is repeated calculations for different values. Imagine you need to calculate the final scores of each student in a class of 30 students. Performing the same calculations for each student requires time and is an exhausting process. In situations like this, loops are extremely helpful. We can specify the calculations within the code block of the loop, and the program can automatically calculate the scores of each student. Using loops, the burdensome process of calculations is reduced to only a few lines of code!

Iteration and Iterables

Let's understand the concept of iteration and iterables first. These terms pop up commonly when working with this concept! Iteration refers to a concept in programming where a set of statements, or a code block is executed repeatedly. Programming languages provide several language features to make it easier for us to implement this feature. Loops are a programming structure that implements this concept. They repeat a set of specified instructions unless told otherwise.

Another important concept is iterables. An iterable is an object that is iterated upon, that is, you can go to each of its elements one by one, and access them. Sequences such as lists and strings are examples of iterables in Python.

Iteration and Iterables

These concepts will become clearer once we move on to the examples.

Loops

Loops are a programming structure that perform the task of iteration. That is, they iterate over a collection of objects. Each programming language has different types of loops. However, there are two kinds of loops that are more common and present in most programming languages; for loops and while loops.

Let's see the implementations of both of them in Python.

For Loops

For loops are used to iterate over a sequence of elements. They are used when a code block needs to be repeatedly executed a known number of times.

In Python, for loops can be used in two ways; using the range keyword and without using the range keyword. range keyword is used to specify how many times the code block of the loop needs to be repeated. It always takes an integer (a variable of type int or a value of type int) as a parameter.

For example, suppose you want to print a list of numbers from 0 to 9. This is an integer sequence, and hence the range keyword is used.

PYTHON
1#prints a sequence of numbers from 0 to 9
2for i in range(10):
3    print(i)

The range keyword can also be used to access sequences using len() method and indexing property. In the below example, len() gives the length of the list (which is 5 here). The loop is thus repeated 5 times, and each time an element from the list is accessed using indexing to print all elements in the list.

PYTHON
1#prints all values in the vegetables list using indices
2vegetables = ["tomato", "potato", "onion", "lettuce", "carrot"]
3for i in range(len(vegetables)):
4    print(vegetables[i])

For loops can be used without the range keyword as well. In that case, elements in the sequence are directly accessed by specifying the variable name of the iterable.

PYTHON
1#prints all values in the vegetables list one by one
2vegetables = ["tomato", "potato", "onion", "lettuce", "carrot"]
3for i in vegetables:
4    print(i)

While Loops

While loops are another type of loops that are used to iterate over a sequence of elements under a certain condition. If the condition is true, the loop keeps executing, but once the condition becomes false, the loop stops executing.

The execution of while loops can be understood by the following illustration.

While Loops

Consider a similar example of printing the first 10 integers. Unlike for loops, in while loops a variable needs to be initialized before the loop. This is because the while loop condition requires the value of the said variable. In the example below, we initialize i before the loop, and keep incrementing it until all the first 10 integers are printed.

PYTHON
1i = 0
2while i < 10:
3    print(i)
4    i += 1

Note: += is the unary or increment operator. It is used when a variable needs to be incremented by 1. This is a common notation that you will see in while loops!

Let's look at another example where we specify a different condition. This loop keeps executing until it encounters an odd element from the list numbers.

PYTHON
1# loop stops once odd number is encountered from the list
2i = 0
3numbers = [0, 2, 4, 5, 7]
4while (numbers[i] % 2) == 0:
5    print(numbers[i])
6    i += 1
7print("Odd number found!")

Python while loops also have an else statement. While the condition is true, the loop executes, and if the condition becomes false then it falls into the else condition and executes the code block there. However, this statement is usually omitted. For example,

PYTHON
1i = 0
2while i < 10:
3    print(i)
4    i += 1
5else:
6    print("i is greater than 10")

Let's test your knowledge. Fill in the missing part by typing it in.

How many times will the following loop be executed?

PYTHON
1fruits = ["apple", "mango", "strawberry", "grapes", "orange", "watermelon", "peach"]
2fruits.pop()
3
4for i in fruits:
5    print(i)

Write the missing line below.

Are you sure you're getting this? Is this statement true or false?

The following code block on execution will generate an error.

PYTHON
1numbers = [0, 2, 4, 5, 7]
2for i in range(numbers):
3    print(numbers[i])

Press true if you believe the statement is correct, or false otherwise.

Important Tips when working with Loops

There are certain important keywords that one must be aware of while working with loops.

  • break statement is an important keyword when working with loops. It can force stop a loop during the execution, before the terminating condition is set to false (in a while loop), or before it completes all its number of iterations (in a for loop).
  • continue statement allows to stop the current iteration and continue with the next. All the code below the continue statement will not be executed and the loop skips to the next iteration.
  • Infinite loop is a condition that occurs if the loop keeps executing forever. This is a common error that may arise when you begin to work with loops. The common cause of the error is usually an error in the loop condition or initialization. The only way to stop an infinite loop is to force stop the execution. This is why it's important to check your loop conditions and initializations, and be careful with them else your program will never stop executing!

Build your intuition. Is this statement true or false?

The letter 'p' will not be printed in the execution of following code block.

PYTHON
1text = "Loops"
2i = 0
3while i < len(text):
4  if text[i] == "o":
5      i += 1
6      continue
7  print(text[i])
8  i += 1

Press true if you believe the statement is correct, or false otherwise.

Are you sure you're getting this? Click the correct answer from the options.

What is the result of the execution of following code block?

PYTHON
1a = 5
2while a <= 5:
3    if a < 5:
4        break
5    print(a)

Click the option that best answers the question.

  • The program will loop indefinitely
  • The value of a will be printed once
  • The value of a will be printed 5 times
  • The loop will not be executed

Summary

Iterations are an important concept in programming. Like functions, iterations help us reduce the number of lines of code that need to be written, and helps in code reusability and modularity. Moreover, loops allow us to specify the number of times the code needs to be reused (or repeated), or the specific condition under the code block needs to be reused.

One Pager Cheat Sheet

  • In this lesson, we will learn about loops and iterations in programming, to automate the process of applying operations to collections of elements.
  • Iteration and iterables such as lists and strings are key concepts in programming which can be implemented through the use of loops.
  • Loops are a programming structure used for iteration that are usually implemented with for and while loops in different programming languages.
  • For loops are used to iterate over a sequence of elements, either using the range keyword to specify the number of repetitions or directly accessing elements in an iterable.
  • While loops are used to iterate over a sequence of elements until a certain condition is met, typically by initializing a variable before the start of the loop and using unary operators to increment or decrement the value of the variable.
  • The for loop will iterate through the list fruits (which contains 6 elements) and print each element per iteration, resulting in the loop being executed 6 times.
  • The code will generate an error because range() expects an integer as the argument, not a list.
  • One must be careful to use the break and continue statements correctly to avoid an Infinite loop, as forcing an execution stop is the only way to terminate it.
  • The code prints all the letters in "Loops" except for 'o', which was skipped due to the continue statement in the while loop, leaving 'p' as the last character.
  • The while loop will continue indefinitely as long as the condition a <= 5 is True.
  • Iterations are an important concept in programming that helps us reduce code quantity and promote code reusability and modularity by allowing us to specify the number of times a code block needs to be repeated or conditions that specify its reuse.