CH - 7 Control Flow
Conditional statements (if, elif, else) and how they control program flow
Control flow in Python refers to the order in which the code is executed. Python provides tools to control the flow of a program, like decision making structures and loops.
- If Statements: These are used to run a block of code only if a specific condition is true. If the condition is false, the code block will be skipped. This allows programs to make decisions. For example, you might use an if statement to check if a user has entered the correct password before allowing them to proceed.
- If else Statements: Sometimes, you may want to provide an alternative action if the condition in the `if` statement is false. This is where the `else` clause comes in. With `if else` statements, your program can choose between two different blocks of code based on whether a condition is true or false.
- Elif Statements: In cases where you have more than two possible outcomes, you can use `elif` (elseif) to check multiple conditions in sequence. The first condition that evaluates to true will trigger its corresponding code block.
- Nested If-Else Statements: In some situations, you may need to evaluate multiple layers of conditions. A nested if-else structure allows you to place one if or else statement inside another, creating a hierarchy of conditions. This is useful when you need to make further decisions based on a previous result. For example, after verifying if a person is eligible for a discount, you might further check if they qualify for an additional promotion. While nested structures add complexity, they enable more granular decision-making within your program.
Example of a simple if-else statement is as follows:
weather = "rainy" # Example value
if weather == "rainy":
print("Take an umbrella!")
else:
print("No need for an umbrella")