Skip to main content
Bash Scripting – Complete Beginner to Advanced Guide
CHAPTER 07 Intermediate

Conditional Statements

Updated: May 16, 2026
20 min read

# Conditional Statements

Welcome to Chapter 7! Conditional statements give your programs the power to make decisions. Based on conditions, your code can take different paths — just like you decide whether to carry an umbrella based on the weather.

---

1. Introduction

In real life, you make decisions constantly: *"If it's raining, take an umbrella. Otherwise, wear sunglasses."* Programming works the same way. Conditional statements evaluate a condition (True or False) and execute different code blocks accordingly.

---

2. Learning Objectives

  • Write if, if-else, and if-elif-else statements.
  • Use nested conditionals.
  • Apply the ternary operator.
  • Use match-case (Python 3.10+).
  • Build a grade calculator project.

---

3. The if Statement

```python id="py7_ex1" age = 18

if age >= 18: print("You are an adult! ✅") print("You can vote.")

# If condition is False, the block is skipped temperature = 15 if temperature > 30: print("It's hot!") # This won't execute

1

if Statement Flow: ┌──────────┐ │ Condition │ └────┬─────┘ │ ┌─────┴─────┐ │ True? │ False? ▼ ▼ ┌─────────┐ (skip) │ Execute │ │ block │ └─────────┘

1234
---

## 4. if-else Statement

python id="py7_ex2" score = 45

if score >= 50: print("PASSED ✅") else: print("FAILED ❌")

12
### Practical Example

python id="py7_ex3" number = int(input("Enter a number: "))

if number % 2 == 0: print(f"{number} is EVEN") else: print(f"{number} is ODD")

1234
---

## 5. if-elif-else Ladder

python id="py7_ex4" score = 78

if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" elif score >= 60: grade = "D" else: grade = "F"

print(f"Score: {score} → Grade: {grade}")

1

elif Ladder Flow: ┌──────────────┐ │ score >= 90? │──Yes──→ Grade A └──────┬───────┘ No ┌──────────────┐ │ score >= 80? │──Yes──→ Grade B └──────┬───────┘ No ┌──────────────┐ │ score >= 70? │──Yes──→ Grade C └──────┬───────┘ No ┌──────────────┐ │ score >= 60? │──Yes──→ Grade D └──────┬───────┘ No └──────────────→ Grade F

1234
---

## 6. Nested if Statements

python id="py7_ex5" age = 25 has_id = True

if age >= 18: if has_id: print("Access granted! ✅") else: print("Please bring your ID. 🪪") else: print("Sorry, you must be 18+. ❌")

1234
---

## 7. Ternary Operator (Conditional Expression)

python id="py7_ex6" age = 20 status = "Adult" if age >= 18 else "Minor" print(status) # Adult

# Nested ternary (use sparingly!) score = 85 grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F" print(f"Grade: {grade}") # B

1234
---

## 8. Match-Case (Python 3.10+)

python id="py7_ex7" command = "start"

match command: case "start": print("Starting the system... 🟢") case "stop": print("Stopping the system... 🔴") case "restart": print("Restarting... 🔄") case _: print("Unknown command! ❓")

1234
---

## 9. Truthy and Falsy Values

python id="py7_ex8" # Falsy values: False, 0, 0.0, "", [], {}, (), None # Everything else is Truthy

name = "" if name: print(f"Hello, {name}!") else: print("Name is empty!") # This runs

items = [1, 2, 3] if items: print(f"List has {len(items)} items") # This runs

1234
---

## 10. Mini Project: Grade Calculator

python id="py7_project" print("=" * 45) print(" 📊 STUDENT GRADE CALCULATOR") print("=" * 45)

name = input(" Student Name: ") math_score = float(input(" Math Score (0-100): ")) science_score = float(input(" Science Score (0-100): ")) english_score = float(input(" English Score (0-100): "))

average = (math_score + science_score + english_score) / 3

if average >= 90: grade, remark = "A+", "Outstanding! 🌟" elif average >= 80: grade, remark = "A", "Excellent! 🎉" elif average >= 70: grade, remark = "B", "Good Job! 👍" elif average >= 60: grade, remark = "C", "Satisfactory 📝" elif average >= 50: grade, remark = "D", "Needs Improvement ⚠️" else: grade, remark = "F", "Failed ❌"

print("\n" + "=" * 45) print(f"{'REPORT CARD':^45}") print("=" * 45) print(f" {'Student':<15}: {name}") print(f" {'Math':<15}: {math_score}") print(f" {'Science':<15}: {science_score}") print(f" {'English':<15}: {english_score}") print(f" {'Average':<15}: {average:.1f}") print(f" {'Grade':<15}: {grade}") print(f" {'Remark':<15}: {remark}") print(f" {'Status':<15}: {'PASSED ✅' if average >= 50 else 'FAILED ❌'}") print("=" * 45) ``

---

11. Common Mistakes

  1. 1. Using = instead of ==: if x = 5 is assignment, not comparison.
  1. 2. Forgetting the colon: if x > 5 needs a : at the end.
  1. 3. Wrong indentation: All code in an if-block must be indented equally.
  1. 4. Overly complex nesting: Flatten with elif or early returns.

---

12. Best Practices

  • Use elif instead of nested if when possible.
  • Keep conditions simple and readable.
  • Use truthy/falsy checks: if items: instead of if len(items) > 0:.
  • Use the ternary operator for simple assignments.

---

13. Exercises

  1. 1. Write a program that checks if a number is positive, negative, or zero.
  1. 2. Build a leap year checker.
  1. 3. Create a ticket pricing system based on age.
  1. 4. Write a program that finds the largest of three numbers.
  1. 5. Build a simple login system with username and password check.

---

14. MCQs with Answers

Q1: What keyword handles multiple conditions? A) else if B) elif C) elseif D) elsif Answer: B

Q2: What does the ternary operator look like? A) x ? y : z B) y if x else z C) x then y else z D) if x: y else: z Answer: B

Q3: Which value is falsy? A) 1 B) "hello" C) [] D) True Answer: C — Empty list is falsy.

Q4: What ends an if statement header? A) Semicolon B) Colon C) Parenthesis D) Curly brace Answer: B

Q5: match-case was introduced in Python: A) 3.8 B) 3.9 C) 3.10 D) 3.11 Answer: C

Q6: What is the _ in match-case? A) Error handler B) Wildcard/default C) Break D) Continue Answer: B

Q7: Can elif exist without if? A) Yes B) No Answer: B

Q8: if 0: evaluates to: A) True B) False C) Error D) None Answer: B — 0 is falsy.

Q9: Can we have if without else? A) Yes B) No Answer: A

Q10: What does not True return? A) True B) False C) None D) Error Answer: B

---

15. Interview Questions

  1. 1. What are truthy and falsy values? Falsy: False, 0, 0.0, "", [], {}, (), None. All others are truthy.
  1. 2. Difference between if-elif and multiple if statements? elif stops at first True; multiple ifs check all conditions independently.
  1. 3. What is match-case in Python? Structural pattern matching (3.10+), similar to switch-case but more powerful with pattern matching.
  1. 4. Can conditions have side effects? Yes, but it's generally discouraged for readability.
  1. 5. What is short-circuit evaluation in conditionals? Python stops evaluating and/or as soon as result is determined.

---

16. Summary

  • if executes code when condition is True.
  • elif handles multiple conditions sequentially.
  • else catches everything not matched by if/elif.
  • Ternary operator: value_if_true if condition else value_if_false.
  • match-case (3.10+) provides structural pattern matching.
  • Use truthy/falsy values for cleaner conditions.

---

17. Next Chapter Recommendation

In Chapter 8: Loops in Python, you'll learn to repeat code with for and while` loops, and build a number guessing game! 🚀

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·