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.
In this lesson, we will explore the concepts of indentation and execution flow in Python. Understanding these concepts is crucial for writing clear and error-free code. Indentation helps define the structure of your code, while execution flow determines the order in which your code runs. These concepts are fundamental in programming and are particularly useful in scenarios involving functions, loops, and conditional statements.
Indentation in Python refers to the spaces at the beginning of a code line. Unlike many other programming languages, Python uses indentation to define the scope of loops, functions, and other constructs. This means that all the lines of code within a particular block must be indented at the same level.
For example:
def greet():
print("Hello, World!")
print("Welcome to Python programming.")
In the above code, both print statements are part of the greet
function because they are indented at the same level.
Let's delve deeper into the key concepts of indentation and execution flow:
Consider the following example:
print("Start of the program")
def greet():
print("Hello, World!")
print("Welcome to Python programming.")
print("Before calling the function")
greet()
print("After calling the function")
In this example, the execution flow is as follows:
greet
function (but do not execute it yet).greet
function, which prints "Hello, World!" and "Welcome to Python programming."Let's look at some more examples to understand these concepts better:
# Example 1: Simple function with indentation
def add(a, b):
result = a + b
return result
print(add(5, 3)) # Output: 8
# Example 2: Conditional statements with indentation
def check_even_odd(number):
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
check_even_odd(4) # Output: 4 is even
check_even_odd(7) # Output: 7 is odd
In these examples, indentation is used to define the scope of the function and the conditional statements.
Here are some common mistakes to avoid and best practices to follow:
As you become more comfortable with basic indentation and execution flow, you can explore advanced techniques such as nested functions, loops, and exception handling. These techniques often require careful attention to indentation to ensure correct execution.
# Example of nested functions
def outer_function():
print("This is the outer function")
def inner_function():
print("This is the inner function")
inner_function()
outer_function()
Let's implement a more complex example that combines multiple concepts:
def process_numbers(numbers):
for number in numbers:
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
numbers_list = [1, 2, 3, 4, 5, 6]
process_numbers(numbers_list)
In this code, we define a function process_numbers
that takes a list of numbers and checks if each number is even or odd. The function uses a loop and conditional statements, both of which require proper indentation.
Debugging and testing are essential parts of writing reliable code. Here are some tips:
unittest
or pytest
.import unittest
def add(a, b):
return a + b
class TestMathFunctions(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
self.assertEqual(add(-1, 1), 0)
if __name__ == '__main__':
unittest.main()
When approaching problems related to indentation and execution flow, consider the following strategies:
In this lesson, we covered the importance of indentation and execution flow in Python. These concepts are fundamental for writing clear and error-free code. By mastering these basics, you will be well-equipped to tackle more complex programming challenges. Remember to practice regularly and explore further applications to deepen your understanding.
For further reading and practice, consider the following resources: