3.3 - Conditional Execution Using If Statement
3.3 - Conditional Execution Using If Statement
Flow of execution
if condition :
code block
Example 2:
1 num = -5.2
2
3 absolute_num = num
4
5 if num < 0:
6 absolute_num = -num
7
8 print("Absolute value of", num, "is", absolute_num)
Output
Example 3:
1 x = 1000
2 y = 123
3
4 min_value = x
5
6 if y < min_value:
7 min_value = y
8
9 print("Minimum of", x, "and", y, "is", min_value)
Output
if statements can have else part to make a choice between two code
blocks.
if condition :
code block1
else :
code block2
Output
Try it!
Write a program that takes an integer as input from the user, call it
X . Then the program should display either The number X is even
Show answer
Chained if-elif-else statement
1 income = 20000
2
3 if income < 12000:
4 tax = 0.0
5 elif income < 30000:
6 tax = income * 15.0 / 100
7 elif income < 100000:
8 tax = income * 20.0 / 100
9 else: # if all above were False i.e. income >= 100000
10 tax = income * 25.0 / 100
11
12 print("Your tax is", tax)
1 money = 5000.0
2
3 if money > 0.0:
4 print("Positive balance")
5 elif money > 1000.0:
6 print("You're rich! Go celebrate!")
7 else:
8 print("Uh-oh. No money.")
Output
Positive balance
1 x = 10
2 if x > 0:
3 print("Positive")
4 else:
5 if x < 0:
6 print("Negative")
7 else:
8 print("Zero")
1 x = 10
2 if x > 0:
3 print("Positive")
4 elif x < 0:
5 print("Negative")
6 else:
7 print("Zero")
You can use either nested or chained conditionals, but note that nested
conditional can easily become hard to read.
Correct indentation is essential!
Sometimes, incorrect indentation may not give an error but it may lead to
unexpected program.
1 income = 1000
2
3 if income < 12000:
4 print("You don't have to pay tax.")
5 tax = 0.0
6 else:
7 print("You have to pay tax.")
8 tax = income * 15.0 / 100 # this line should be indented
9
10 print("Your tax is", tax)
Try it
x is even
x is an odd number multiple of 3
x is an odd number not multiple of 3
Show answer