If Elif Else
If Elif Else
if condition:
expression
z=4
if z % 2 == 0: #true
print("z is even")
z=5
if z%2 == 0: #false
print("checking" +str(z))
print("z is even)
it doesnot print the output beacuse expression is part of if.to print the odd
parts we need else
else
if condition:
expression
else:
expression
example
z=5
if z%2 == 0: #false
print("checking" +str(z))
print("z is even)
else:
print("z is odd")
elif
if condition:
expression
elif condition:
expression
else :
expression
example
z=3
if z%2== 0:
print("z is divisible by 2") #false
elif z%3 ==0
print("z is divisible by 3") #true
else:
print("z is neither divisible by 2 nor by 3")
but if both if and elif conditions hold, python doesnot print both ,it
prints 1st if condition
z=6
if z%2== 0:
print("z is divisible by 2") #false
elif z%3 ==0
print("z is divisible by 3") #true
else:
print("z is neither divisible by 2 nor by 3")
Exercise
Exercise
if
It's time to take a closer look around in your house.
Two variables are defined in the sample code: room, a string that tells you which
room of the house we're looking at, and area, the area of that room.
Instructions
Examine the if statement that prints out "Looking around in the kitchen." if room
equals "kit".
Write another if statement that prints out "big place!" if area is greater than 15.
# Define variables
room = "kit"
area = 14.0
Exercise
Exercise
Add else
On the right, the if construct for room has been extended with an else statement so
that "looking around elsewhere." is printed if the condition room == "kit"
evaluates to False.
Can you do a similar thing to add more functionality to the if construct for area?
Instructions
100 XP
Add an else statement to the second control structure so that "pretty small." is
printed out if area > 15 evaluates to False.
# Define variables
room = "kit"
area = 14.0
It's up to you now! Make a similar addition to the second control structure to
further customize the messages for different values of area.
Instructions
Add an elif to the second control structure such that "medium size, nice!" is
printed out if area is greater than 10.
# Define variables
room = "bed"
area = 14.0