Introduction
Conditional statements are used to make decisions in a Python program. They allow the program to execute different blocks of code based on whether a condition is True or False.
Definition
A conditional statement is a control structure that executes a specific block of code only when a given condition is satisfied.
Types of Conditional Statements
Python provides the following conditional statements:
ifStatementif-elseStatementif-elif-elseStatement- Nested
ifStatement
1. if Statement
The if statement executes a block of code only if the specified condition is True.
Syntax
if condition:
# statements
Example
age = 18
if age >= 18:
print("You are eligible to vote.")
Output
You are eligible to vote.
2. if-else Statement
The if-else statement executes one block of code if the condition is True and another block if it is False.
Syntax
if condition:
# True block
else:
# False block
Example
num = 7
if num % 2 == 0:
print("Even Number")
else:
print("Odd Number")
Output
Odd Number
3. if-elif-else Statement
The if-elif-else statement is used to check multiple conditions. Once a condition is found to be True, the corresponding block is executed.
Syntax
if condition1:
# Block 1
elif condition2:
# Block 2
elif condition3:
# Block 3
else:
# Default block
Example
marks = 82
if marks >= 90:
print("Grade A+")
elif marks >= 80:
print("Grade A")
elif marks >= 70:
print("Grade B")
elif marks >= 60:
print("Grade C")
else:
print("Fail")
Output
Grade A
4. Nested if Statement
A nested if statement is an if statement placed inside another if statement.
Syntax
if condition1:
if condition2:
# statements
Example
age = 20
citizen = True
if age >= 18:
if citizen:
print("Eligible to vote")
Output
Eligible to vote
Comparison Operators Used in Conditions
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | a == b |
!= | Not equal to | a != b |
> | Greater than | a > b |
< | Less than | a < b |
>= | Greater than or equal to | a >= b |
<= | Less than or equal to | a <= b |
Logical Operators
| Operator | Description | Example |
|---|---|---|
and | Returns True if both conditions are true | a > 0 and b > 0 |
or | Returns True if at least one condition is true | a > 0 or b > 0 |
not | Reverses the result | not(a > b) |
Example
age = 22
has_id = True
if age >= 18 and has_id:
print("Entry Allowed")
else:
print("Entry Denied")
Output
Entry Allowed
Flowchart of an if-else Statement
Start
|
v
Check Condition
/ \
True False
| |
Execute IF Execute ELSE
| |
\ /
End
Advantages of Conditional Statements
- Enable decision-making in programs.
- Improve program flexibility.
- Handle different situations based on user input.
- Make code more organized and readable.
Applications
Voting eligibility checks
Student grading systems
ATM transactions
Login authentication
Online shopping discounts
Traffic signal control
