Conditional statements are used to control the flow of a program based on certain conditions. They allow the program to make decisions and execute different blocks of code depending on whether a condition is True or False.
if StatementThe if statement executes a block of code only if the condition is True.
if condition:
# code block
age = 18
if age >= 18:
print("You are eligible to vote")
Output
You are eligible to vote
if-else StatementThe if-else statement provides an alternative block of code when the condition is False.
if condition:
# code if True
else:
# code if False
num = 5
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
Output
Odd number
if block runselse block runsif-elif-else StatementThe if-elif-else statement is used when there are multiple conditions to check.
if condition1:
# code block 1
elif condition2:
# code block 2
elif condition3:
# code block 3
else:
# default code
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
else block runsif Statementnum = 10
if num > 0:
if num % 2 == 0:
print("Positive Even Number")
if-elif-elseelse is optionalif → executes code if condition is Trueif-else → provides two choicesif-elif-else → handles multiple conditions