Understand Sequential Flow and Introduce Conditional Logic
In this step, we will explore the concept of sequential flow in programming and introduce conditional logic, which allows programs to make decisions.
Sequential flow is the most basic type of program execution. Instructions are executed one after another, from top to bottom.
The lab environment has already created a file named sequential.py for you in the ~/project directory. Locate this file in the WebIDE's file explorer on the left panel and open it.
Add the following code to sequential.py:
print("First instruction")
print("Second instruction")
print("Third instruction")
Save the file. To run the script, open the integrated terminal in the WebIDE and execute the following command:
python ~/project/sequential.py
You will see the output printed in the exact order the print statements appear in the script:
First instruction
Second instruction
Third instruction
This demonstrates sequential flow. However, programs often need to behave differently based on certain conditions. This is where conditional logic comes in. The most fundamental conditional statement in Python is the if statement, which executes a block of code only if a specified condition is true.
The basic syntax of an if statement is:
if condition:
## Code to execute if the condition is true
## This block must be indented
Now, replace the content of sequential.py with the following code to include an if statement:
x = 10
print("Before the if statement")
if x > 5:
print("x is greater than 5")
print("After the if statement")
Save the file and run it again:
python ~/project/sequential.py
The output will be:
Before the if statement
x is greater than 5
After the if statement
The condition x > 5 is true, so the indented code block inside the if statement is executed.
Now, let's see what happens when the condition is false. Modify sequential.py by changing the value of x to 3:
x = 3
print("Before the if statement")
if x > 5:
print("x is greater than 5")
print("After the if statement")
Save the file and run it:
python ~/project/sequential.py
The output will be:
Before the if statement
After the if statement
This time, the condition x > 5 is false, so the code block inside the if statement is skipped. This simple example illustrates how the if statement introduces decision-making into our programs.