Day8 Conditional Statement in Python
Day8 Conditional Statement in Python
Source: www.youtube.com/@RishabhMishraOfficial
Chapter - 09
P y t h o n N o t e s b y R i s h a b h M i s h ra
1. 'if' Conditional Statement
The if statement is used to test a condition and execute a block of code only if
the condition is true.
Syntax:
if condition:
# Code to execute if the condition is true
Example:
age = 26
if age > 19:
print("You are an adult")
P y t h o n N o t e s b y R i s h a b h M i s h ra
2. 'if-else' Conditional Statement
The if-else statement provides an alternative block of code to execute if the
condition is false.
Syntax:
if condition:
# Code to execute if the condition is true
else:
# Code to execute if the condition is false
Example:
temperature = 30
if temperature > 25:
print("It's a hot day.")
else:
print("It's a cool day.")
P y t h o n N o t e s b y R i s h a b h M i s h ra
3. 'if-elif-else' Conditional Statement
The if-elif-else statement allows to check multiple conditions and execute
different blocks of code based on which condition is true.
Syntax:
if condition1:
# Code to execute if condition1 is true
elif condition2:
# Code to execute if condition2 is true
else:
# Code to execute if none of the above conditions are true
Example:
Grading system: Let’s write a code to classify the student’s grade based on their
total marks (out of hundred).
score = 85
if score >= 90:
print("Grade - A")
elif score >= 80:
print("Grade - B")
elif score >= 70:
print("Grade - C")
else:
print("Grade - D")
P y t h o n N o t e s b y R i s h a b h M i s h ra
Syntax:
if condition1:
# Code block for condition1 being True
if condition2:
# Code block for condition2 being True
else:
# Code block for condition2 being False
else:
# Code block for condition1 being False
... ..
Example:
Number Classification: Let's say you want to classify a number as positive,
negative, or zero and further classify positive numbers as even or odd.
number = 10
if number > 0: # First check if the number is positive
if number % 2 == 0:
print("The number is positive and even.")
else:
print("The number is positive and odd.")
else: # The number is not positive
if number == 0:
print("The number is zero.")
else:
print("The number is negative.")
5. Conditional Expressions
Conditional expressions provide a shorthand way to write simple if-else
statements. Also known as Ternary Operator.
P y t h o n N o t e s b y R i s h a b h M i s h ra
Syntax:
value_if_true if condition else value_if_false
Example:
age = 16
status = "Adult" if age >= 18 else "Minor"
print(status)
Conditional Statements- HW
Q1: what is expected output and reason?
value = None
if value:
print("Value is True")
else:
print("Value is False")
P y t h o n N o t e s b y R i s h a b h M i s h ra