Conditional Execution
Conditional Execution
Conditional Execution
• 5 = 5 is True or False?
• It takes two operands a and b and returns the remainder when a is divided by b
• Example:
5%2 = 1 => 5 = 2*2 + 1
8%3 = 2 => 8 = 2*3 + 2
Logical Operators
• There are 3 logical operators
- and
- or
- not
x and y is true only when both x and y are true, else it is false
x or y is false only when both x and y are false, else it is true
not x is true if x is false, and false if x is true
Logical Operators
• Example:
-n%2 == 0 or n%3 == 0
It is true if either or both of the conditions is true, that is, if the number is divisible by 2 or 3
-not (x > y)
It is true if x > y is false, that is, if x is less than or equal to y
Conditional Execution
• In python the decision control instruction can be implemented using:
1. if statement
- Colon is placed after the condition to state which instructions to execute once the condition is true
- The instructions to execute are placed after an indent of 4 spaces. Brackets are optional, but indent
is a must. All the instructions within the intent are treated as one chunk and executed together.
if-statement
• Example
if x > 0 :
print('x is positive’)
The indented block is the body of the if statement. There has to be at least 1 statement.
If there is no statement to execute, you can simply type pass. Example:
if x < 0 :
pass
if-statement
• The interpreter will execute the body of if statement until the statements are within the
indent.
• Once the indent ends, the interpreter exits the if-statement and moves to next
statement, which would always be executed whether the condition satisfies or not.
if-else statement
• Syntax:
• if condition_is_true :
execute_this_statement
else :
execute_another_statement
• if statement executes a statement when a given condition is true. If we want to execute different statement
when the condition is false, we use the else block.
• else block is followed by a colon and then in the next line we indent to indicate start of the body or block of
statements to execute
if-else statement
• Example:
if x%2 == 0 :
print('x is even')
else :
print('x is odd')
if-elif-else statement
• if-else is used when there are only 2 possibilities
• When there are >2 possibilities, use if-elif-else statement, elif is short for else if
• Syntax:
if possibility1:
execute_this_statement
elif possibility2
execute_another_statement
elif possibility3
execute_another_statement
.
.
.
else:
execute_a_different_statement
if-elif-else statement
if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal’)
if x == y:
print('x and y are equal')
else:
if x < y:
print('x is less than y’)
else:
print('x is greater than y')
Conditional Expressions (ternary if-
else)
• Syntax
a if condition else b