Here is a clear, simple, and exam-oriented explanation of Decision Making Statements in Python, suitable for BCA/MCA/B.Tech students.
Decision Making Statements in Python
Decision-making statements allow a program to choose different actions based on certain conditions.
In Python, decisions are made using conditional statements, mainly:
ifif-elseif-elif-else- Nested
if - Short-hand
ifandif-else
These statements allow Python programs to behave differently depending on inputs or logical conditions.
1. The if Statement
Used to check a condition.
If the condition is True, the block of code inside if runs.
Syntax:
if condition:
statement(s)
Example:
age = 20
if age >= 18:
print("You are an adult.")
Output:
You are an adult.
2. The if-else Statement
Used when you need two possible outcomes.
Syntax:
if condition:
statement(s)
else:
statement(s)
Example:
marks = 40
if marks >= 50:
print("Pass")
else:
print("Fail")
Output:
Fail
3. The if-elif-else Statement
Used when checking multiple conditions.
Syntax:
if condition1:
statement 1
elif condition2:
statement 2
elif condition3:
statement 3
else:
default statement
Example:
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Fail")
Output:
Grade B
4. Nested if Statement
An if inside another if.
Used for multiple-level checking.
Example:
age = 25
citizen = True
if age >= 18:
if citizen:
print("Eligible to vote")
else:
print("Not a citizen")
else:
print("Underage")
5. Short-Hand if Statement
If the body contains only one statement, you can write it on one line.
Example:
x = 10
if x > 5: print("Greater")
6. Short-Hand if-else (Ternary Operator)
Single-line version of if-else.
Syntax:
value_if_true if condition else value_if_false
Example:
age = 17
status = "Adult" if age >= 18 else "Minor"
print(status)
Output:
Minor
7. Using Logical Operators in Decision Making
Combine multiple conditions using:
andornot
Example:
age = 20
has_id = True
if age >= 18 and has_id:
print("Entry allowed")
8. Using Membership and Identity Checks
Example using in:
fruits = ["apple", "banana"]
if "apple" in fruits:
print("Apple found")
Example using is:
x = None
if x is None:
print("Value is None")
9. Indentation (Important for Exams)
Python uses indentation instead of braces {}.
Indentation defines block structure.
Wrong (no indentation):
if x > 5:
print("Hello")
Correct:
if x > 5:
print("Hello")
10. Example Program: Odd or Even
num = int(input("Enter number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
11. Example Program: Largest of Three Numbers
a = 10
b = 25
c = 15
if a > b and a > c:
print("a is largest")
elif b > a and b > c:
print("b is largest")
else:
print("c is largest")
Summary
| Statement | Use |
|---|---|
if | Single condition |
if-else | Two outcomes |
if-elif-else | Multiple conditions |
Nested if | Condition inside condition |
| Shorthand if | One-line statement |
| Ternary | Inline if-else |
