If...Else...
Introduction:
- Python supports logical conditions from mathematics:
- Equals:
a == b - Not Equals:
a != b - Less than:
a < b - Less than or equal to:
a <= b - Greater than:
a > b - Greater than or equal to:
a >= b
- Equals:
Else Statement:
- The
elsekeyword catches anything not caught by preceding conditions.
Syntax of If-Else:
python
if boolean_expression:
statement(s)
else:
statement(s)
- Indentation is crucial. Statements inside the
ifandelseblocks must be properly indented.
Examples:
If-Else with Condition True:
pythona = 2 b = 4 if a < b: print(a, 'is less than', b) else: print(a, 'is not less than', b)- Output:
2 is less than 4
- Output:
If-Else with Condition False:
pythona = 5 b = 4 if a < b: print(a, 'is less than', b) else: print(a, 'is not less than', b)- Output:
5 is not less than 4
- Output:
Nested If-Else:
pythona = 2 b = 4 c = 5 if a < b: print(a, 'is less than', b) if c < b: print(c, 'is less than', b) else: print(c, 'is not less than', b) else: print(a, 'is not less than', b)Output:
2 is less than 4 5 is not less than 4
Summary:
- Python if-else statements are fundamental for controlling the flow of your program based on conditions. Practice writing if-else statements to become proficient in using conditional logic in your programs