This document explains Python conditions and branching, including comparison operators, Boolean logic, if/else/elif statements, and practical examples for decision-making in code.
This document covers Python conditions and branching, including comparison operators, Boolean logic, if/else/elif statements, and practical examples for decision-making in code.
Conditions and branching in Python allow programs to make decisions based on comparisons and logical operations. These features are essential for controlling program flow.
Comparison operations compare values and produce Boolean results:
| Operator | Description | Example | Result |
|---|---|---|---|
| == | Equal to | 6 == 7 | False |
| != | Not equal to | 2 != 6 | True |
| > | Greater than | 6 > 5 | True |
| < | Less than | 2 < 6 | True |
| >= | Greater or equal | 5 >= 5 | True |
| <= | Less or equal | 2 <= 5 | True |
Comparison can be applied to numbers and strings.
Branching enables different code execution based on conditions.
Executes code if the condition is true:
1age = 19
2if age >= 18:
3 print("You will enter")
4print("Move on")
Executes code if the condition is false:
1age = 17
2if age >= 18:
3 print("You will enter")
4else:
5 print("Go see Meatloaf")
6print("Move on")
Checks additional conditions if previous ones are false:
1age = 18
2if age > 18:
3 print("You can enter")
4elif age == 18:
5 print("Go see Pink Floyd")
6else:
7 print("Go see Meatloaf")
8print("Move on")
Logical operators combine Boolean values:
| Operator | Description | Example | Result |
|---|---|---|---|
| not | Negation | not True | False |
| or | Either | True or False | True |
| and | Both | True and False | False |
Logical operators are used to build complex conditions.
Conditions and branching are fundamental for decision-making in Python. Mastering comparison and logical operators, along with branching statements, enables flexible and intelligent program control.
(4) Python does not have a built-in xor logical operator; use combinations of not, or, and and instead.
| Concept | Description |
|---|---|
| A. if | 1. Executes code if condition is true |
| B. else | 2. Executes code if all previous conditions are false |
| C. elif | 3. Checks additional condition if previous is false |
| D. not | 4. Negates a Boolean value |
A-1, B-2, C-3, D-4.
Logical operators can be used to combine multiple conditions in Python branching statements.
True. Logical operators like and, or, and not allow combining multiple conditions.