Flow of Control in Python Notes
Flow of Control refers to the order in which statements are executed in a program. In Python, there are three main types of flow control:
- Sequential Flow: In this flow, statements are executed one after another, in the same order as they appear in the code.
- Conditional Flow: The execution of code depends on a condition being true or false, using constructs like
if
,if-else
, andif-elif-else
. - Iterative Flow: This flow involves repeating a block of code multiple times using loops, such as
for
andwhile
.
Indentation
Python uses indentation to define blocks of code. All the statements within a block must be indented at the same level. This is critical in Python, as it defines the structure and flow of control statements (e.g., conditional and loops).
Conditional Statements in Python
Conditional statements allow you to execute specific code blocks based on conditions. These include:
1. if
Statement
The simplest form of a conditional statement that checks whether a condition is True
and executes the associated block.
if condition:
statement1
statement2
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
2. if-else
Statement
This extends the if
statement by specifying an action if the condition is False
.
if condition:
statement1
else:
statement2
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
3. if-elif-else
Statement
Used when you have multiple conditions to evaluate. The elif
keyword stands for “else if” and allows checking multiple conditions.
if condition1:
statement1
elif condition2:
statement2
else:
statement3
temp = int(input("Enter temperature: "))
if temp > 100:
print("Gaseous state")
elif temp < 0:
print("Solid state")
else:
print("Liquid state")