Python Conditional Statements
Table of Contents
Description
Conditional statements are used to execute certain blocks of code based on whether a condition is true or false. These statements allow decision-making in a program, controlling the flow based on logical conditions.
Python supports the following conditional statements:
if
if-else
if-elif-else
Prerequisites
- Understanding of Boolean expressions (True/False)
- Familiarity with comparison and logical operators.
- Basic knowledge of indentation and code blocks
Examples
Here's a simple program in Python:
# Example 1: Simple if statement
x = 10
if x > 5:
print("x is greater than 5") # Executes because condition is True
# Example 2: if-else statement
age = 17
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote") # Executes because age < 18
# Example 3: if-elif-else ladder
score = 85
if score >= 90:
print("Grade: A")
elif score >= 75:
print("Grade: B") # Executes
elif score >= 60:
print("Grade: C")
else:
print("Grade: D")
# Example 4: Nested if
num = -3
if num != 0:
if num > 0:
print("Positive number")
else:
print("Negative number") # Executes
Real-World Applications
User authentication: Check if credentials match.
E-commerce platforms: Apply discounts based on cart value.
Banking systems: Validate transactions and limits.
Game development: Check player lives, score, level status.
Healthcare apps: Display health alerts based on condition thresholds.
Where topic Can Be Applied
Decision-making in control flow.
Form validations in web development.
Branching logic in AI model pipelines.
IoT systems: Sensor-triggered logic.
Finance apps: Rule-based interest or fraud detection.
Resources
Topic video source
A comprehensive video
Watch
Python pdf
pdf on topic
Visit
Interview Questions
What is the difference between if and if-else?
Can elif be used without else?
Is if a statement or a function in Python?
What happens if you forget to indent after if?
Write a Python code to check if a number is even or odd using if-else.