Python - Selection Statements


This lesson covers the following topics:


The Selection Structure


Also known as a conditional structure, a selection structure is a programming feature that performs different processes based on whether a boolean condition is true or false. Selection structures use relational operators to test conditions.


description of gif

In [4]:
# Here is the syntax of a ONE-WAY selection in Python.
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

password = input("Please enter your password: ")

if password == "12345":
    print("Access Granted.")
Please enter your password: 12345
Access Granted.
In [6]:
# Here is the syntax of a TWO-WAY selection in Python.
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

password = input("Please enter your password: ")

if password == "12345":
    print("Access Granted.")
    
else:
    print("Access Denied.")
Please enter your password: 748936578792346
Access Denied.

There are a few rules to point out regarding the syntax of selection statements.

  • The conditional keywords are if, elif, and else.
    • if - begins an "if" block
    • elif - (same as "else if") pythons way of saying "if the previous conditions were not true, then try this condition"
    • else - catches anything which isn't caught by the preceding conditions
  • The conditional test evaluates to True or False.
  • The conditional test is followed by a colon.
  • The conditional body must be indented properly (use tab).


Relational Operators


Python supports the usual logical conditions from mathematics. These conditions can be used in several ways, most commonly in "if statements" and loops.

Operator Meaning Sample Condition Evaluates To
== equal to 5 == 5 True
!= not equal to 5 != 5 False
< less than 3 < 10 True
<= less than or equal to 5 <= -2 False
> greater than 7 > 7 False
>= greater than or equal to 7 >= 7 True


Logical Operators


Logical operators allow you to write composite conditional statements. Although there are more logical operators, the three listed below are the most commonly used.

Operator Meaning Sample Condition Evaluates To
not (!) (unary operator) negates a boolean value not True (!True) False
and (binary operator) both sides need to be True to evaluate to True True and False False
or (binary operator) at least one side needs to be True to evaluate to True True or False True


Examples



Calculate Grade Program (the wrong way)

In [3]:
# Here is an example of "independent" conditional statements.  (this program doesn't work as intended!!!)
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

grade = 91

if grade >= 90:
    print("You got an A!")

if grade >= 80:
    print("You got a B!")
    
if grade >= 70:
    print("You got a C!")
    
if grade >= 60:
    print("You got a D!")
    
if grade < 60:
    print("You got an F!")
You got an A!
You got a B!
You got a C!
You got a D!

As you can see, the code above doesn't work as intended. The issue is that these are all independent "if" statements. That means each one will be tested. Since 91 is greater than 90, 80, 70, and 60, all of those conditionals evaluate to True and are executed. To fix this, we can link these tests together using if, elif, and else.


Calculate Grade Program (the right way)

In [11]:
# Here is an example of "dependent" conditional statements.  (this program works as intended)
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

grade = int(input("Please enter your grade: "))

if grade >= 90:
    print("You got an A!")

elif grade >= 80:
    print("You got a B!")
    
elif grade >= 70:
    print("You got a C!")
    
elif grade >= 60:
    print("You got a D!")
    
else:
    print("You got an F!")
Please enter your grade: 88
You got a B!

As you can see, the code now works as intended. These conditional tests are now "linked" together with if, elif, and else keywords. This means that once one of them is true, the rest will be skipped, giving us the correct printout.

This example is not meant to show that one method is superior to another. It is meant to show you that you need to program the appropriate structure of your conditional statements to properly solve the problem at hand.


Below are 3 programs that are coded differently, but do the same thing.

In [5]:
# Here is an example of "nested" conditional statements.  (notice how the indentation rules are still applied)
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

age = int(input("What is your age? "))

if age >= 16:
    if age >= 18:
        print("You can vote.")
    else:
        print("You can drive.")
else:
    if age >= 13:
        print("You are a teenager.")
    else:
        print("You are not a teenager yet.")
What is your age? 21
You can vote.
In [6]:
# Here is an example of that same program as above, but with logical operators.
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

age = int(input("What is your age? "))

if age >= 18:
    print("You can vote.")

if age >= 16 and age < 18:
    print("You can drive.")
    
if age >= 13 and age < 16:
    print("You are a teenager.")
    
if age < 13:
    print("You are not a teenager yet.")
What is your age? 17
You can drive.
In [7]:
# Here is an example of that same program as above, but with "dependent" conditional statements.
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

age = int(input("What is your age? "))

if age >= 18:
    print("You can vote.")

elif age >= 16:
    print("You can drive.")
    
elif age >= 13:
    print("You are a teenager.")
    
else:
    print("You are not a teenager yet.")
What is your age? 12
You are not a teenager yet.