4.1 Decision Making: if-else, if-elif-else (BT101CO)
Decision making in Python allows a program to execute specific blocks of code only when certain conditions are met. These are often called Conditional Statements.
1. The if Statement
The simplest form of decision making. If the condition is True, the indented block of code runs. If it is False, Python skips it.
# Syntax:
if condition:
# code to execute if True
# Example:
age = 20
if age >= 18:
print("You are an adult.")
2. The if-else Statement
This provides an alternative path. If the if condition is False, the else block executes. It is an "either-or" scenario.
# Syntax:
if condition:
# runs if True
else:
# runs if False
# Example:
marks = 35
if marks >= 40:
print("Result: Pass")
else:
print("Result: Fail")
3. The if-elif-else Ladder
When you have multiple conditions to check, you use elif (short for "else if"). Python checks them in order from top to bottom. As soon as one is True, it executes that block and exits the entire ladder.
# Syntax:
if condition1:
# Block 1
elif condition2:
# Block 2
else:
# Default Block
# Example (Grading System):
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
4. Key Rules to Remember
- The Colon (
:): Everyif,elif, andelseline must end with a colon. - Indentation: Python uses whitespace to define blocks of code. All lines inside a specific condition must be indented equally (usually 4 spaces).
- The
elseis Optional: You can have anifwithout anelse, but you cannot have anelsewithout a precedingif.
5. Nested if Statements
You can place an if statement inside another if statement for more complex "Problem Solving" logic.
Example:
num = 10
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
6. Solved Example: BMI (Body Mass Index) Calculator
Let's build a program that takes weight and height, calculates BMI, and categorizes it.
# Step 1: Get user input
weight = float(input("Enter your weight in kg: "))
height = float(input("Enter your height in meters: "))
# Step 2: Calculate BMI formula: weight / height^2
bmi = weight / (height ** 2)
print(f"Your BMI is: {bmi:.2f}")
# Step 3: Decision Making with if-elif-else
if bmi < 18.5:
print("Category: Underweight")
elif bmi >= 18.5 and bmi < 25:
print("Category: Normal weight")
elif bmi >= 25 and bmi < 30:
print("Category: Overweight")
else:
print("Category: Obese")
| Tool | Type | Purpose in Example |
|---|---|---|
float() | Type Casting | Converted text input into numbers. |
** | Arithmetic | Squared the height for the formula. |
bmi:.2f | Formatting | Rounded the output for readability. |
if-elif-else | Decision | Categorized the result. |