Python Conditionals
Conditional Statements: Conditional statements are used to make decisions
in Python based on certain conditions. These are essential elements of
control structures.
if statement: The if statement is used to else statement: The else statement is
execute a block of code if a specified used in conjunction with if. It specifies a
condition is True. block of code to be executed if the
condition in the if statement is False.
Example Code Example Code
x = 10 x = 3
if x > 5: if x > 5:
print('x is greater than 5') print('x is greater than 5')
else:
Output: print('x is not greater than
5')
x is greater than 5
This code assigns the value 10 to the Output:
variable x and then checks if x is greater x is not greater than 5
than 5; if it is, it prints the message "x is
This code assigns the value 3 to the
greater than 5.
variable x and prints "x is not greater
than 5" because the condition x > 5 is
not met.
elif statement: The elif statement is Ternary (conditional) operator: The
used for handling multiple conditions. It ternary operator provides a concise
allows you to check alternative way of writing simple if-else
conditions when the initial if condition is statements. It's useful for assigning
False. values to variables based on
conditions.
1|Page
Example Code: Example Code:
x = 5 x = 7
if x > 5: result = 'x is greater than 5' if
x > 5 else 'x is not greater than
print('x is greater than 5')
5'
elif x == 5:
print(result)
print('x is equal to 5')
else:
print('x is less than 5')
Output:
Output:
x is equal to 5
x is greater than 5
The code sets x to 7, then uses a
This code assigns the value 5 to the
variable x and prints "x is equal to 5" conditional expression to assign "x is
because the condition x == 5 is met in greater than 5" or "x is not greater than
the elif branch. 5" to the variable result, which is then
printed as "x is greater than 5."
2|Page