If statement#
if
construct allows to create cases in the code based on conditions:
if condition:
# Execute some code if condition is True
elif condition2:
# Execute some code only if condition is False and condition2 is True
else:
# Execute some code only if both condition and condition2 are False
elif
and else
are optional blocks. Code inside each block needs to be indented.
Example use#
number = 10
if number < 5:
print("%g is less than 5." % (number))
elif number < 12:
print("%g is less than 12." % (number))
else:
print("%g is greater or equal to 12." % (number))
# If statements in one line
a = 1 if number == 5 else 0
print(a)
10 is less than 12.
0
Exercises#
Flow control: What is the difference between the output of the following code samples:
a = 5
if a < 5:
print("foo")
elif a == 5:
print("bar")
else:
print("boom")
a = 4
if a < 5:
print("foo")
elif a == 5:
print("bar")
else:
print("boom")
a = 4
if a <5:
print("foo")
elif a == 5:
print("bar")
print("boom")
Answer
First: bar
Second: foo
Third: foo boom