Video Lesson:
Lesson Transcript:
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 function and which are not.
Take this function for example:
def say_hello():
print("Hello World")
print("Welcome to AlgoCademy!")
Both print statements would run when say_hello() is called because they have the same level of indentation (2 spaces).
As for this code:
def say_hello():
print("Hello World")
print("Welcome to AlgoCademy!")
print("Outside the function!")
The unindented line print("Outside the function!") is not part of the function. Even more, it marks the end of the function.
The output of this program is:
Outside the function!
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:
print("It's a beautiful day.")
def say_hello():
print("Hello coders!")
print("Welcome to AlgoCademy!")
print("Students are joining.")
say_hello()
print("We'll learn about functions.")
prints:
It's a beautiful day.
Students are joining.
Hello coders!
Welcome to AlgoCademy!
We'll learn about functions.
This is how the Python interpreter goes through this code line by line:
print("It's a beautiful day.") # <- Print "It's a beautiful day."
print("It's a beautiful day.")
def say_hello(): # <- A function say_hello() is about to be defined
print("It's a beautiful day.")
def say_hello():
print("Hello coders!") # <- Indented line, so this is part of the function. Not executing the print tho.
print("It's a beautiful day.")
def say_hello():
print("Hello coders!")
print("Welcome to AlgoCademy!") # <- Indented line, so this is also part of the function. Not executing the print tho.
print("It's a beautiful day.")
def say_hello():
print("Hello coders!")
print("Welcome to AlgoCademy!")
print("Students are joining.") # <- Unindented line, so the function definition is over.
# Print "Students are joining."
print("It's a beautiful day.")
def say_hello():
print("Hello coders!")
print("Welcome to AlgoCademy!")
print("Students are joining.")
say_hello() # <- Function call of say_hello(). Executing the code inside function:
# Print "Hello coders!"
# Print "Welcome to AlgoCademy!"
print("It's a beautiful day.")
def say_hello():
print("Hello coders!")
print("Welcome to AlgoCademy!")
print("Students are joining.")
say_hello()
print("We'll learn about functions.") # <- Print "We'll learn about functions."
Assignment
Follow the Coding Tutorial and let's practice with indentation and execution flow!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
