Start learning free

LESSON 140 OF 673 · FOR LOOPS - LOOPING OVER LISTS

For Loop - Indentation & Execution Flow in Python

Lesson

Indentation refers to the whitespaces at the beginning of a code line. Python uses indentation to indicate which lines of code are part of a for loop and which are not.

Take this code for example:

languages = ["Python", "Java", "JavaScript"]

for language in languages:
  print("I love " + language)
  print("I want to get better at it")

Both print statements are part of the loop since they have the same level of indentation (2 spaces).

This means that both messages will be printed for every language in the languages list. The output of that code would be:

I love Python
I want to get better at it
I love Java
I want to get better at it
I love JavaScript
I want to get better at it

As for this code:

languages = ["Python", "Java", "JavaScript"]

for language in languages:
  print("I love " + language)
print("I want to get better at them")

The unindented line print("I want to get better at them") is not part of the loop. Even more, it marks the end of the loop.

This means that only print("I love " + language) will be executed for every language in the languages list.

Then, when the for loop is over, the print("I want to get better at them") will be executed only once.

The output of this program would be:

I love Python
I love Java
I love JavaScript
I want to get better at them

Execution flow

Lastly, note that the execution of a program always begins on the first line. The code is then executed one line at a time from top to bottom. This is known as execution flow and is the order a program in Python executes code.

For example, this program:

fruits = ["banana", "apple", "kiwi"]

print("I'm hungry!")

for fruit in fruits:
  print("I'm gonna eat:")
  print(fruit)

print("I love my life!")

prints:

I'm hungry!
I'm gonna eat:
banana
I'm gonna eat:
apple
I'm gonna eat:
kiwi
I love my life!


Assignment:

Add a for loop inside our code in the editor such that the final program would print:

Today we'll learn about:
Python
Java
JavaScript
Let's code!
STEP 1 OF 1
    Ctrl + Enter to check