Skip to main content
Enchanted Code

Python 3 if statements

tutorial, python

Intro

This tutorial will teach you about if statements in Python. This tutorial is intended to be read after my python-for-beginners tutorial.

Requirements

  • Know basics of Python 3 if not read here
  • Knowledge of logic gates will help

What are they?

If statements allow you to add logic into your application. This allows you to create programs that will react differently depending on inputs given. They use operators to create “decisions”, these operators could be equality, greater than, less than, etc. A condition can be combined with keywords such as “or” and “and”.

Operators

If you don’t know any operators I have listed some important ones here.

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

If

Let’s start simple. If statements start with the command “if” then they have some kind of check and then a colon. You may notice code after the if statement if indented by 4 spaces, this tells Python that specific code is part of the if statement. It will also only run if the statement is true.

x = 10

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

if x > 10:
    print("more than 10")

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

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

When run this code should output: is equal to 10. This is because all of the other if statements were false.

Elif

But what happens if you want to select the first statement matching and skip executing the rest. Well a “elif” can do just that.

As you can see below, the elif statement is put below the first if statement.

No other code must be between a if and elif statement at the same indentation level that the if was defined.

Multiple elif statements are possible

x = 10

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

When run you will see that only the first matching statement will run; this will produce a output of: is equal to 10.

Else

Ok, but what happens if we don’t have a condition that will accept anything else. Well your in luck as Python has that as well its called “else”. It must go at the end of a if statement chain. As it is designed to always be true, it does not require any operators and can just be else:.

x = 11

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

When this code is run you will see that the else statement is run as there are no other statements that matched. You should get an output of not equal to 10.

Multiple Operators

If you want to have multiple operators inside one if statement you can. In this example I will use “and”, which requires all statements to be true. You can use “or” which will only require one statement to be true.

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

a = 12

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

When run you will see that it will only run when “a” is less than 20 and more than 5. You should get the output of: amazing!.

Simple Calculator

Now we will resume our calculator from the last tutorial and put the new knowledge to use.

We want to allow our calculator to also subtract. Here is what you will need:

  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
  4. if +, add them together and store in answer variable, then skip to step 7
  5. elif -, 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 below.

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

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

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

Now we should test whether we can make the error we coded will output, so lets use 20 and 5 and the operator “*”.

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

As we can see our error message worked. Now have a go and test the application with some more numbers using both the addition and subtraction mode.

Well done, you should now know all about if statements. Have a go and practice by adding more math operations into the calculator like multiply and divide.

The next feature you should probably learn is iteration using “while” and “for”.