Lecture 4 a Handouts Decision Making
Lecture 4 a Handouts Decision Making
1. The if Statement
The if statement is used to execute a block of code only if a specified condition is true.
Syntax:
if condition:
# Code to execute if the condition is True
Example:
x = 10
if x > 5:
print("x is greater than 5")
In this example, the condition x > 5 evaluates to True, so the statement inside the if block is
executed.
Syntax:
if condition:
# Code to execute if the condition is True
else:
# Code to execute if the condition is False
Example:
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
Here, since x > 5 evaluates to False, the code inside the else block is executed.
1
3. The if-elif-else Statement
The if-elif-else statement is used for checking multiple conditions. It evaluates
conditions in sequence and executes the code block of the first condition that evaluates to
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 all conditions are False
Example:
x = 10
if x > 15:
print("x is greater than 15")
elif x > 5:
print("x is greater than 5 but less than or equal to 15")
else:
print("x is less than or equal to 5")
In this example, the second condition x > 5 is True, so the corresponding block is executed,
and the remaining conditions are skipped.
4. Nested if Statements
An if statement can be nested inside another if statement to check multiple levels of
conditions.
Syntax:
if condition1:
if condition2:
# Code to execute if both condition1 and condition2 are True
Example:
x = 20
if x > 10:
if x % 2 == 0:
print("x is greater than 10 and is even")
In this example, the outer condition checks if x > 10. Inside it, the nested if checks if x is
even using the modulus operator.
2
5. Using Logical Operators in Decision-Making
Logical operators like and, or, and not can be used to combine multiple conditions.
Example:
x = 7
if x > 5 and x < 10:
print("x is between 5 and 10")
Here, the and operator ensures that both conditions must be True for the block to execute.