Enchanted Code

Selection In Python

6 minutes read

Intro

Selection is an important concept to learn, it allows you to add logic into your program. In Python selections are constructed by using “if statements”. This tutorial will provide the essential knowledge required to add selection into your Python programs.

What Is Selection?

Expanding on what was said in the intro, selection allows you to add logic into your application. This allows you to create programs that will react differently depending on the inputs received.

Operators

Operators are used to adjust how these “decisions” are made. They can be: equality, greater than, less than, etc. Operators in Python can also be combined with boolean logic such as “AND”, “OR” and “NOT”. This allows for complex decisions to be formed.

Common Operators

Here’s some of the common operators available in Python:

Operator Meaning
== Equal
!= Not Equal
> More Than
< Less Than
>= More Than Or Equal
<= Less Than Or Equal

Example

As a recap of boolean logic, here’s a pseudocode example:

1
2
3
A = 2
B = is A equal to 4 or A less than to 10
output B

Now converting it into Python code:

1
2
3
a = 2
b = a == 4 or a < 10
print(b)

Running the code we should get “True” as an output.

“if”

As mentioned in the intro; Python handles selection through “if statements”. Now let’s see an example Python program that uses if statements.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
x = 10

if x < 10:
    print("less than 10")

if x != 20:
    print("is not equal to 20")

x = x - 10

if x == 10:
    print("is equal to 10")

if x == 0:
    print("is equal to 0")

Have a guess at what you think might happen?

View Answer

When run, this code should generate the output shown below.

1
2
is not equal to 20
is equal to 0

Let’s take a look at the first if statement:

1
2
if x < 10:
    print("less than 10")
  • The first line tells Python we are creating a if statement.
  • Have a look at the structure
    • We start the statement by using the “if” keyword
    • Then we have our decision (using an operator)
    • Then we end the line with a colon
  • To tell Python which section of code should be run when the decision is TRUE we indent the code after the statement.

You may notice that every if statement is checked, what happens if we want to match the first ’truthy’ statement and skip the rest? Let’s move on to the next section and see.

“elif”

To run the first matching expression and skip the rest, an “elif” statement can be used.

1
2
3
4
5
6
7
8
x = 10

if x == 10:
    print("is equal to 10")
elif x != 10:
    print("not equal to 10")
elif x > 5:
    print("more than 5")

Have a guess at what you think might happen?

View Answer

When run, this code should generate the output shown below.

1
not equal to 10

In Python we can put “elif” expressions after an “if”. We can add as many as we want after the initial expression, as seen in this example it has three possible decisions but only one will run.

But what happens if we want a “catch all” decision, well Python can do this too! See the next section.

“else”

To add a “catch all” in Python we can add a “else” expression to our code.

1
2
3
4
5
6
7
8
x = 11

if x == 10:
    print("equal to 10")
elif x > 20:
    print("more than 20")
else:
    print("not equal to 10")

What do you think happens?

View Answer

When run, this code should generate the output shown below.

1
not equal to 10

Using an “else” expression we ensure that our decisions always have a fallback, meaning if all of the selections result in FALSE, it will run anything in our “else” block.

We can use an “else” expression as the last decision. That means we have to at least defined an “if” block, we can put any “elif” expressions in-between; as shown in the example code above.

Multiple Operators

All of the examples shown so far have only had one operator per expression, but what happens if we want to have two decisions resulting in one outcome. Well we chain operators using boolean logic.

TIP: “and” and “or” are not the only keywords that can be used.

1
2
3
4
a = 12

if a < 20 and a > 5:
    print("amazing!")

Take a moment and think what should happen in this code?

View Answer

When run, this code should generate the output shown below.

1
amazing!

As we can see our “if” statement will only run when both decisions are TRUE. This is because we have chained two operators with an “and”.

Simple Calculator

Now we can put our knowledge into use with a practical project, building a calculator that can perform addition and subtraction depending on the users decision.

Here’s a basic calculator that currently performs only addition, expand it to add subtraction as well (created in a previous tutorial.

1
2
3
4
5
6
7
8
9
num_a = input("Enter Number A? ")
num_b = input("Enter Number B? ")

num_a = float(num_a)
num_b = float(num_b)

answer = num_a + num_b

print("The sum of", num_a, "+", num_b, "is", answer)

Follow these steps as a guide for what we need our program to do:

  1. get two numbers from the user as separate variables
  2. convert both to float or int data-types
  3. ask user what operation to use (+ or -)
  4. if +, add them together and store in answer variable, then skip to step 7
  5. else if -, subtract them and store in answer variable
  6. else, show a warning
  7. output the answer

Try to code your own version before looking at the completed code.

Completed Code

This code may look different to yours’. Don’t worry for now, check if your program functions first by moving on to the testing section.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
num_a = input("Enter Number A? ")
num_b = input("Enter Number B? ")

num_a = float(num_a)
num_b = float(num_b)

operation = input("Operation (+ or -) ? ")

if operation == "+" or operation == "-":
    answer = 0
    if operation == "+":
        answer = num_a + num_b
    elif operation == "-":
        answer = num_a - num_b
    print("The sum of", num_a, operation, num_b, "is", answer)
else:
    print("Unsupported operation character")

Testing Our Calculator

Lets test our application with numbers 14 and 20 and the operator “+”, this should give the answer of 34.

1
2
3
4
Enter Number A? 14
Enter Number B? 20
Operation (+ or -) ? +
The sum of 14 + 20 is 34

Now we should test whether our error handling functions, so lets use 20 and 5 and the operator “*”.

We should get the below output if our error message works.

1
2
3
4
Enter Number A? 14
Enter Number B? 20
Operation (+ or -) ? *
Unsupported operation character

Have a go and test your calculator with more numbers using both addition and subtraction, to ensure it works as expected.

Next Steps

How about you expand the calculator and add multiplication and division into the program. This will reinforce your knowledge of selection in Python and allow you to use your calculator to aid you in the future.

See Also

What Is Pip?

A Python 3 tutorial to show how to use Python's pip command...

Buy Me A Coffee