Control Flow: if, elif, else
Control flow refers to the order in which individual statements, instructions, or function calls are executed or evaluated in a program. In Python, control flow is facilitated by the use of three key statements: if, elif, and else.
4.1 What is Control Flow?
Control flow allows your program to make decisions and execute certain blocks of code based on conditions. The key control flow statements in Python include:
- if: Executes a code block if a specified condition is true.
- elif: Tests an additional condition if the previous if condition is false.
- else: Executes a code block if all preceding if and elif conditions are false.
4.2 The if Statement
The if statement checks a condition and executes the corresponding block of code only if the condition is true. The syntax is:
Code Editor - python
4.3 The else Statement
The else statement follows an if statement and runs a code block when the condition is false:
Code Editor - python
4.4 The elif Statement
elif (short for else if) allows checking for multiple conditions in sequence:
Code Editor - python
4.5 Indentation is Crucial
In Python, indentation defines code blocks. Proper indentation is essential to avoid errors:
Code Editor - python
4.6 Nested Conditions
Nested conditions allow placing an if statement within another if statement, enabling more complex logic:
Code Editor - python
4.7 Try It Yourself
- Write a program to determine if a number is positive, negative, or zero.
- Ask the user for their marks and print an appropriate grade.
- Write a nested if statement to check the age and if a voter ID is available.
Summary
Understanding control flow with if, elif, and else is essential for implementing decision-making logic in Python programs. It allows for building dynamic and responsive applications.