Control Flow (if, elif, else)¶
Python uses standard control flow statements (if, elif, else) to make decisions based on boolean conditions.
Python Indentation Rule¶
Unlike C, Java, or JavaScript, which use curly braces {} to delimit blocks of code, Python uses indentation (whitespace).
- PEP 8 standard recommendation is 4 spaces per indentation level.
- Do not mix tabs and spaces.
- Statements that start a block (
if,for,def,class) always end with a colon:.
Example: Indentation in Python
The if, elif, and else Statements¶
Syntax¶
Example: Letter Grading System
marks = 78
if marks >= 90:
grade = "A"
elif marks >= 80:
grade = "B"
elif marks >= 70:
grade = "C"
else:
grade = "F"
print("Assigned Grade:", grade)
Output
Assigned Grade: C
Comparison: Value Equality (==) vs Identity (is)¶
==compares the values of two objects.ischecks whether two variables point to the exact same memory location (id(a) == id(b)).
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 == list2) # True (same values)
print(list1 is list2) # False (different objects in memory)
# Comparing with None: Always use 'is' or 'is not'
value = None
if value is None:
print("Value is None")
Truth Value Testing (Truthy and Falsy)¶
In Python, any object can be tested for truth value:
Falsy Values¶
The following objects evaluate to False in conditions: - Constants: None, False - Numeric zeros: 0, 0.0, 0j - Empty sequences and collections: "", (), [], {}, set()
All other objects evaluate to True (Truthy).
Example: Checking Truthiness
Conditional Expression (Ternary Operator)¶
Assign a value conditionally in a single readable line:
Syntax¶
Pattern Matching (match / case in Python 3.10+)¶
Python 3.10 introduced structural pattern matching: