Decision Making
Decision-making structures allow a program to execute specific blocks of code based on given conditions. Python uses if, elif, and else.
Every day we face choices — if it rains, bring an umbrella; if not, take a casual walk. The same concept applies in programming. With branching, a program can react intelligently to various situations. Instead of running lines of code blindly from top to bottom, a program can decide which step is most appropriate based on the data it receives.
Python uses indentation (not curly braces) to mark code blocks. This makes the code neater and easier to read. The if-elif-else system lets you write complex decision chains without making the code messy. In addition, there is the ternary — a short way to write a simple branch in one line.
Conditional Structure:
- if — checks a single condition
- elif — checks an additional condition (if the previous if is False)
- else — default block if all conditions are False
- Ternary — one-line conditional expression
Code Example
# if - elif - else
score = 85
if score >= 90:
print("Grade A")
elif score >= 80:
print("Grade B")
elif score >= 70:
print("Grade C")
else:
print("Grade D")
# Output: Grade B
# Ternary Expression
status = "Passed" if score >= 70 else "Not Passed"
print(status) # Passed
Code Explanation
First, we create a variable score with the number 85. The first if block checks whether score >= 90 — the result is False because 85 < 90, so the program falls through to the next elif. elif score >= 80 evaluates to True (85 >= 80), so the program prints "Grade B" and skips all the conditions below it. The else block only runs if all the previous conditions are False.
The ternary below is the short version: the variable status is set to "Passed" if score >= 70, or "Not Passed" if not. This is equivalent to a regular if-else but more concise.
Everyday Example
Imagine an app login system. When a user enters a username and password, the program needs to make a decision: if the username is registered and the password matches, allow access; if the password is wrong, display an error message; if the username is not found, redirect to the registration page. The if-elif-else branching is the backbone of logic like this.
username = "admin"
password = "secret123"
if username == "admin" and password == "secret123":
print("Login successful! Welcome.")
elif username == "admin":
print("Wrong password. Try again.")
else:
print("Username not found.")
Summary
Decision-making structures are the foundation of logic in programming. With if, elif, and else, we can build programs that are adaptive and responsive to various conditions. Master branching, and you have mastered one of the most important concepts in Python.