Day 5: Conditional Statements in Python
Making Decisions in Your Code
Introduction
In real life, we make decisions all the time:
- If it rains → take an umbrella
- If marks ≥ 90 → Grade A
- If balance is low → show warning
Similarly, in programming, we use conditional statements to control the flow of execution.
What are Conditional Statements?
Conditional statements allow a program to make decisions based on conditions.
They help programs:
- Execute different blocks of code
- Respond dynamically to input
- Implement logic like real-world systems
Core Idea
# if condition is True -> run code
# else -> skip or run something else
1. if Statement
Syntax
if condition:
# code block
Example
age = 18
if age >= 18:
print("You can vote")
Runs only when condition is True
2. if-else Statement
Syntax
if condition:
# True block
else:
# False block
Example
num = 5
if num % 2 == 0:
print("Even")
else:
print("Odd")
3. if-elif-else Statement
Used when multiple conditions exist
Syntax
if condition1:
# block1
elif condition2:
# block2
else:
# default block
Example
marks = 94
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Fail")
Important Rule
Only ONE block executes
First True condition wins
4. Nested Conditions
Condition inside another condition
Example
age = 20
has_id = True
if age >= 18:
if has_id:
print("Entry Allowed")
else:
print("ID required")
else:
print("Underage")
Important Concepts (Must Understand)
Truthy & Falsy Values
if 0:
print("Hello")
else:
print("World")
Output: World
Truth Table
- 0, None, False, "" → Falsy
- Everything else → Truthy
Order Matters
marks = 90
if marks >= 50:
print("Pass")
elif marks >= 90:
print("Topper")
Output: Pass (because first condition matched)
Practice Problems
- Check whether a number is positive or negative.
- Check whether a number is even or odd.
- Find the greater number between two numbers.
Intermediate Level
- Find the greatest among three numbers.
- Check whether a given year is a leap year.
- Create a grade system based on marks:
- 90 and above → Grade A
- 75 to 89 → Grade B
- 50 to 74 → Grade C
- Below 50 → Fail
Advanced Level
- Check whether a given number is a palindrome.
- Build logic for an ATM withdrawal system:
- Check if balance is sufficient
- Check if amount is a multiple of 100
- Create a login system:
- Validate username and password
- Show success or error message
.png)
.png)
.png)
