Program execution happens sequentially in Python - the Python interpreter reads a program just like you are reading this page: one line at a time, from left to right and top to bottom. The interpreter executes operations and functions in the order that it encounters them. This is called control flow.
Share this step
Program execution happens sequentially in Python – the Python interpreter reads a program just like you are reading this page: one line at a time, from left to right and top to bottom. The interpreter executes operations and functions in the order that it encounters them. This is called control flow.
Without control flow expressions, a program is simply a list of statements that are sequentially executed. With control flow, you can execute certain code blocks conditionally and/or repeatedly and these basic building blocks can be combined to create sophisticated code.
Python uses if, elif (short for else if), and else keywords to create control flow structures in your program. Imagine all these keywords are traffic controllers telling the control flow where to go.
Watch the video to get an overview about the three control flow expressions in Python and to understand how they work.
Let’s look at each of each of these control flow expressions in more depth.
Control Flow Expressions in Python
1. if statement
The if statement is one of the most well-known control flow statement types. It checks a condition and executes one of two functions:
For example:
Let us say we want to know if the input value of a is positive or negative. We use the if statement and set two conditions: if a is greater than 0, print ‘Its positive’, and if a is less than 0, print ‘Its negative.’
If the set condition is True, the code in the following block is executed.
If the set condition is False, the code in the following block is ignored.
The code snippet highlights this code behaviour:
Code:
a=20ifa>0:...print("Its Positive")...
Output:
Its Positive
Code:
ifa<o:...print("Its Negative")
Observer that print was not executed because condition didn’t evaluate to true.
2. elif and else
An if statement can be optionally followed by one or more elif blocks, and a catch-all else block if all of the conditions are false.
The code snippet highlights the code behaviour using elif and else code blocks:
Code:
defcodeblock(x):...ifx<0:...print("Its Negative")...elifx==0:...print("Equal to Zero")...elif0<x<5:print("Positive but smaller than 5")...else:print("Positive and larger than or equal to 5")...codeblock(-10)