Conditional Statement in Python perform different computations or actions depending on whether a specific Boolean constraint evaluates to True
or False
.
Frequently, a program needs to skip over some statements, execute a series of statements repetitively, or choose between alternate sets of statements to execute.
That is where control structures come in. A control structure directs the order of execution of the statements in a program
Decision-making is as important in any programming language as it is in life. Decision-making in a programming language is automated using conditional statements, in which Python evaluates the code to see if it meets the specified conditions.
Conditional statements are one of the most fundamental concepts in programming. The ability to write even the simplest of programs is impossible without it. Thus, in order to write complex algorithms and code, a programmer must have a solid understanding of how to effectively utilize conditional statements.
if
statement
if else
statement
Nested if
statement
if
...elif
Shorthand if
statement
Shorthand if-else
statement
if
Statement¶The If statement is the most fundamental decision-making statement, in which the code is executed based on whether it meets the specified condition.
It has a code body that only executes if the condition in the if statement is true. The statement can be a single line or a block of code.
It allows for conditional execution of a statement or group of statements based on the value of an expression.
These statements begin with the if
keyword followed by a condition which should evaluate to either True
or False
, followed by a colon :
.
The code block comes in the second line indented at the beginning with equal amount of indent. This is the code to be implemented if the condition is met
# syntax of if statement
if expression:
statement # if expression evaluates to True execute block
If expression
is True
, then statement
is executed.
If expression
is False
, then statement
is skipped over and not executed
Note : The colon (:
) following expression
is required.
# example 1
x = 0
y = 5
if x < y:
print('yes')
yes
# example 2
num = 5
if num > 0: # True
print(num, "is a positive number")
5 is a positive number
# example 3
num = 5
if num < 0: # False
print(num, "is a negative number")
# will not output anything
# example 4
country = "Kenya" # strings
person = "Ken"
if person in country: # membership operator
print("Person in country")
Person in country
# example 5
fruits = ["apple","mango","orange","water melon"] # list
if "tomato" in fruits: # falsy membership operator
print("tomato is a fruit")
# this block will not be evaluated
# example 6
fruits = ["apple","mango","orange","water melon"] # list
if "mango" in fruits: # True
print("mango is in fruits")
mango is in fruits
There are two parts to the structure in Python:
one is the parent statement line which defines the statement with if or other keywords and this line must end with a :
(colon).
Two is the child statement(s) which contain the code block to be implemented if the condition is true(in the case of if statement).
The child statement(s) must be indented with four white spaces (or a tab space) at the beginning otherwise an IndentationError will be thrown.
parent statement:
child statement or code block indented
In a Python program, continuous statements that are indented to the same level are considered to be part of the same block.
if
statement¶
if
expression
:
statement 1
statement 2
...
statement n
following statement
Here, all statements after the :
colon at the matching indentation level (statement 1
to statement n
) are considered part of the same block. The entire block is executed if expression
is True
, or skipped over if expression
is False
.
Either way, execution proceeds with following statement
Notice that there is no token that denotes the end of the block. Rather, the end of the block is indicated by a line that is indented less than the lines of the block itself (following statement
).
# example 7
fruits = ["apple","mango","orange","water melon"] # list
if "mango" in fruits: # True membership operator
print("wash mango")
print("peel mango")
print("eat mango")
print("return the fruit basket")
wash mango peel mango eat mango return the fruit basket
if
else
Statement¶This statement is used when both the true and false parts of a given condition are specified to be executed.
When the condition is True, the statement inside the if block is executed; if the condition is False, the statement outside the if block is executed.
if
expression
:
statement(s)
# executed if True
else
:
statement(s)
# executed if False
# example 8
num = 5
if num >= 0: # True
print("Positive or Zero")
else:
print("Negative number")
Positive or Zero
# example 9
x = 20
if x < 50:
print('first block')
print('x is less than 50')
else:
print('second block')
print('x is greater than or equal to 50')
first block x is less than 50
# example 9
x = 120
if x < 50:
print('first block')
print('x is less than 50')
else:
print('second block')
print('x is greater than or equal to 50')
second block x is greater than or equal to 50
if
…elif
…else
¶You can check for many other conditions using elif
(short for else if). The final else evaluates only when no other condition is true.
Note that else and elif statements are optional and you can have one without the other. The first if statement is a must.
if
expression
:
statement(s)
# executed if True
elif
expression 2
:
statement(s)
# executed ifexpression 2
is True
elif
expression 3
:
statement(s)
# executed ifexpression 3
is True
...
else
:
statement(s)
# executed if all other conditions are False
An if statement with elif clauses uses short-circuit evaluation. Once one of the expressions is found to be true and its block is executed, none of the remaining expressions are tested.
# example 10
age = 50
if age >= 55:
print("You are a senior")
elif age < 35:
print("You are a youth")
else:
print("You are middle aged")
You are middle aged
# example 11
age = 26
if age >= 55:
print("You are a senior")
elif age < 35:
print("You are a youth")
else:
print("You are middle aged")
You are a youth
elif statements are useful when you have the need to use multiple if statements.
# example 12
# getting a message from the user
message = input("Whats your message (Hi, Bye, Thank You, Congrats): ")
"""
program responds to the user's greeting if they say
"Hi" or "Bye" or "Thank You" or "Congrats"
"""
if message == "Hi":
print("hello. User said Hi")
elif message == "Bye":
print("have a great day. User said Bye")
elif message == "Thank You":
print("You're welcome. User said Thank You")
elif message == "Congrats":
print("Kudos! User is amazed and saying Congrats")
else:
# if none of the above is True
print("User said something different")
Whats your message (Hi, Bye, Thank You, Congrats): Thank You You're welcome. User said Thank You
# example 12
# getting a message from the user
message = input("Whats your message (Hi, Bye, Thank You, Congrats): ")
"""
program responds to the user's greeting if they say
"Hi" or "Bye" or "Thank You" or "Congrats"
"""
if message == "Hi":
print("hello. User said Hi")
elif message == "Bye":
print("have a great day. User said Bye")
elif message == "Thank You":
print("You're welcome. User said Thank You")
elif message == "Congrats":
print("Kudos! User is amazed and saying Congrats")
else:
# if none of the above is True
print("User said something different")
# example 13
# lets upgrade the previous example
# getting a message from the user
message = input("Whats your message (Hi, Bye, Thank You, Congrats): ")
message_title = message.title()
"""
program responds to the user's greeting if they say
"Hi" or "Bye" or "Thank You" or "Congrats"
"""
if message_title == "Hi":
print("hello. User said Hi")
elif message_title == "Bye":
print("have a great day. User said Bye")
elif message_title == "Thank You":
print("You're welcome. User said Thank You")
elif message_title == "Congrats":
print("Kudos! User is amazed and saying Congrats")
else:
# if none of the above is True
print(f"User said something different : {message}")
Whats your message (Hi, Bye, Thank You, Congrats): thank you You're welcome. User said Thank You
A Nested If Statement is one in which an if
statement is nested inside another if
statement.
This is used when a variable must be processed more than once.
In Nested If statements, the indentation is used to determine the scope of each statement and the precedence.
if
expression
:
statement(s)
# executed if True
if
condition 2
:
statements
else
:
statement(s)
# executed if False
# example 14
num = input()
num = int(num)
if num >= 0:
if num == 0:
print("zero")
else:
print("positive number")
else:
print("Negative number")
-5 Negative number
# example 15
in_desc = """\
Which country would you like to learn about?
('Kenya','Canada','Angola',
'Nigeria','Zambia','Uganda',
'Egypt','China','USA','Japan',
'Germany','Chad','Botswana','France')"
"""
country = input(in_desc)
countries = ('Kenya','Canada','Angola',
'Nigeria','Zambia','Uganda',
'Egypt','China','Japan',
'Germany','Chad','Botswana',
'France','USA')
africa = ["Kenya","Angola","Nigeria",
"Zambia","Egypt","Chad",
"Uganda","Botswana"]
asia = ["China","Japan","India"]
europe = ["Germany","France"]
america = ["Canada"]
country_regions = {
"Kenya":"East Africa",
"Angola":"Central Africa",
"Nigeria":"West Africa",
"Zambia":"South Africa",
"Egypt":"North Africa"
}
if country in countries:
print("country details available...")
if country in africa:
print("African country")
if country in country_regions:
print(f"The country {country} is in {country_regions[country]} region")
else:
print(f"Regional details for country {country} are not provided")
elif country in asia:
print(f"The country {country} is in Asia")
elif country in europe:
print(f"The country {country} is in Europe")
else:
print(f"The country {country} is in America")
else:
print(f"Country {country} not in the list provided")
Which country would you like to learn about? ('Kenya','Canada','Angola', 'Nigeria','Zambia','Uganda', 'Egypt','China','USA','Japan', 'Germany','Chad','Botswana','France')" Africa Country Africa not in the list provided
# example 16
i = 15
# one line if statement
if i>11 : print("i is greater than 11")
i is greater than 11
if-else
statement¶Python supports one additional decision-making entity called a conditional expression. (It is also referred to as a conditional operator or ternary operator in various places in the Python documentation.
expression 1
if
conditional expression
else
expression 2
In the above example, conditional_expr
is evaluated first.
If it is True
, the expression evaluates to expression 1
. If it is False
, the expression evaluates to expression 2
.
Notice the non-obvious order: the middle expression is evaluated first, and based on that result, one of the expressions on the ends is returned.
Here are some examples that will hopefully help clarify
# example 17
age = 12
s = 'minor' if age < 18 else 'adult'
print(s)
minor
# example 18
a = 3
b = 5
print('A') if a > b else print("B")
B
# example 19
'yes' if ('qux' in ['foo','bar','baz']) else "No"
'No'
A common use of the conditional expression is to select variable assignment. For example, suppose you want to find the larger of two numbers.
# example 20
a = 20
b = 25
m = a if a > b else b
print(m)
25
Occasionally, you may find that you want to write what is called a code stub: a placeholder for where you will eventually put a block of code that you haven’t implemented yet.
if
expression
:
pass
# executed if True
else
:
pass
# executed if False
will not produce an Exception
# example 20
# runs without an error
if True:
pass
else:
pass
The if
condition is used to evaluate a block when only one of the conditions listed is True or False
When one of the conditions is False
, then if
-else
condition is used to evaluate the code
When there is a third possible outcome, the elif
statement is used. In a program, any number of elif
conditions can be used.
Evaluation of the elif
block follows the short circuit evaluation.
Write a Program to check if a given year is a leap year.
The given year will be from Keyboard Input.
Instructions:
A year is a leap year if the following conditions are satisfied:
The year is multiple of 400
the year is multiple of 4 and not a multiple of 100
Test your program by testing 1900, 2000, 2022
hint 1900 is not a leap year but 2000 is a leap year
# sample solution
year_input = input()
year = int(year_input)
# write a program to check if year is a leap year
2020
Write a program that checks if a number from input is a multiple of three, five and both three and five.
For multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".
# solution
# will do in class