Practical – 151 : Construct and analyze code segments that use branching statements
✅ What Are Branching Statements?
Branching statements allow you to run specific blocks of code based on conditions.
✨ 1. Simple if Statement
age = 20
if age >= 18:
print(“You are eligible to vote.”)
🔍 Analysis:
- Checks if age is greater than or equal to 18.
- If True, prints the message.
- If False, does nothing.
✨ 2. if-else Statement
number = -5
if number >= 0:
print(“Number is positive.”)
else:
print(“Number is negative.”)
🔍 Analysis:
- One of two blocks is executed.
- Ensures that one and only one path runs.
✨ 3. if-elif-else Ladder
marks = 75
if marks >= 90:
print(“Grade: A”)
elif marks >= 75:
print(“Grade: B”)
elif marks >= 60:
print(“Grade: C”)
else:
print(“Grade: D”)
🔍 Analysis:
- Evaluates conditions in order.
- Executes the first True block, then skips the rest.
✨ 4. Nested if Statements
username = “admin”
password = “1234”
if username == “admin”:
if password == “1234”:
print(“Login successful.”)
else:
print(“Incorrect password.”)
else:
print(“Unknown user.”)
🔍 Analysis:
- One if inside another: useful for multi-level checks.
- Used when decisions depend on multiple related conditions.
✅ Tips for Using Branching:
- Keep conditions clear and readable.
- Use logical operators (and, or, not) for combined conditions.
- Prefer elif over multiple ifs when conditions are mutually exclusive.