Getting Started with Python¶

Conditional Statements in Python¶

Author : Waweru Kennedy¶

Date: 3/3/2022¶

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.

Conditional Statements in Python

  1. if statement

  2. if else statement

  3. Nested if statement

  4. if...elif

  5. Shorthand if statement

  6. 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.

syntax¶

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

In [ ]:
# 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.

In [1]:
# example 1
x = 0
y = 5

if x < y:
    print('yes')
    
yes
In [2]:
# example 2
num = 5
if num > 0: # True
    print(num, "is a positive number")
    
5 is a positive number
In [3]:
# example 3
num = 5
if num < 0: # False
    print(num, "is a negative number")
    
# will not output anything
In [4]:
# example 4
country = "Kenya" # strings
person = "Ken"

if person in country: # membership operator
    print("Person in country")
Person in country
In [6]:
# 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
In [8]:
# example 6

fruits = ["apple","mango","orange","water melon"] # list

if "mango" in fruits: # True
    print("mango is in fruits")
mango is in fruits

Indentation in Python¶

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.

Syntax:¶

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.

Syntax of compound 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).

In [9]:
# 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.

Syntax¶

if expression:
        statement(s) # executed if True
else:
        statement(s) # executed if False

In [42]:
# example 8

num = 5
if num >= 0: # True
    print("Positive or Zero")
else:
    print("Negative number")
Positive or Zero
In [11]:
# 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
In [12]:
# 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.

Syntax¶

if expression:
        statement(s) # executed if True

elif expression 2:
        statement(s) # executed if expression 2 is True

elif expression 3:
        statement(s) # executed if expression 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.

In [13]:
# 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
In [15]:
# 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.

In [17]:
# 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
In [ ]:
# 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")
In [19]:
# 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

Nested If Statement¶

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.

Syntax¶

if expression :
        statement(s) # executed if True

        if condition 2 :
                statements

else:
        statement(s) # executed if False

In [20]:
# 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
In [36]:
# 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

Short hand if Statement¶

Short Hand if statement is used when only one statement needs to be executed inside the if block. This statement can be mentioned in the same line which holds the If statement.

Syntax¶

if condition : statement

Example¶
In [37]:
# example 16

i = 15
# one line if statement
if i>11 : print("i is greater than 11")
i is greater than 11

Short Hand 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.

Syntax¶

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

In [38]:
# example 17

age = 12
s = 'minor' if age < 18 else 'adult'
print(s)
minor
In [39]:
# example 18

a = 3
b = 5
print('A') if a > b else print("B")
B
In [40]:
# example 19
'yes' if ('qux' in ['foo','bar','baz']) else "No"
Out[40]:
'No'

Usage in Variable Assignment¶

A common use of the conditional expression is to select variable assignment. For example, suppose you want to find the larger of two numbers.

In [41]:
# example 20
a = 20
b = 25

m = a if a > b else b
print(m)
25

The Python pass Statement¶

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.

Syntax¶

if expression:
        pass # executed if True
else:
        pass # executed if False

will not produce an Exception

In [44]:
# example 20
# runs without an error
if True:
    pass
else:
    pass

Summary¶

  • 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.

Exercise¶

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:

  1. The year is multiple of 400

  2. the year is multiple of 4 and not a multiple of 100

Test¶

Test your program by testing 1900, 2000, 2022

hint 1900 is not a leap year but 2000 is a leap year

In [46]:
# sample solution

year_input = input()

year = int(year_input)

# write a program to check if year is a leap year
2020

Bonus¶

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".

In [ ]:
# solution

# will do in class

References¶

https://www.analyticsvidhya.com/blog/2021/08/a-comprehensive-guide-to-conditional-statements-in-python-for-data-science-beginners/

https://realpython.com/python-conditional-statements/

https://python.plainenglish.io/september-21-2021-dbe2eae668ba

https://www.guru99.com/if-loop-python-conditional-structures.html