In this lesson we will look at:
- if statements
- Comparison operators (
- else and elif for making either/or decisions
An if statement is used to control whether or not a particular block of code gets to run. Here is an example:
n = 1 if n < 2: print("n is less than 2") print("finished")
Here it is line by line:
1. We set the variable
n to 1.
2. The if statement checks if
n is less than 2 In this case it is, of course.
3. We print n is less than 2.
4. We print finished.
The output of this code is:
n is less than 2 finished
The important thing here is that the first print statement will only run if n is less than 2. You can check this by altering the first line of code to set n to 3:
n = 3 #Changed if n < 2: print("n is less than 2") print("finished")
n is not less than 2, so the first print statement doesn't execute. We say that the test
n < 2 fails.
However, the second print statement still executes because it isn't part of the "body" of the if statement (because it isn't indented). So the code just prints:
Anatomy of an if statement
An if statement generally looks something like this:
if <test>: <body>
<test> is some kind of logical test such as is n less than 2.
<body> is one or more lines of Python code that only run if the test is true.
Important points are:
- The if statement ends in a colon character :
- Each line of the body is indented by exactly 4 spaces
The indentation is vital – it is the only way Python knows which statements are part of the body, and which ones are part of the rest of the program. Each line of the body should be indented by exactly 4 spaces.
At the end of the body, the next line of code should return to the previous level of indentation (the same as the if statement itself).
You don't have to use 4 spaces, but that is the Python standard that most programmers use. You could use 2 spaces or 3 spaces, for example, but most of the Python code you will see on example sites uses 4 spaces. Whatever number of space you choose, it must be exactly the same number on each line.
Avoid using tab characters for indentation, which can cause confusing errors. Always use spaces for indentation.
In the previous sections, we saw the less than operator
<. This is known as a conditional operator.
if n < 2: print("n is less than 2")
Python has several conditional operators. The basic ones are:
x < y | True if value of x is less than value of y, false otherwise |
x > y | True if value of x is greater than value of y, false otherwise |
x == y | True if value of x is exactly equal to value of y, false otherwise |
Notice that the equals operator is
== rather than
=. This is to avoid confusion with assignment:
n == 6 # Tests if n is equal to 6, doesn't change n n = 6 # Changes the value of n to 6
There are three more conditional operators:
x <= y | True if x is less than or equal to y, false otherwise |
x >= y | True if x is greater than or equal y, false otherwise |
x != y | True if x is not equal to y, false otherwise |
It is worth noting that each of the conditions is the exact opposite of one of the others:
x > y | Opposite to
x <= y |
x < y | Opposite to
x >= y |
x == y | Opposite to
x != y |
You might sometimes find yourself dealing with complex conditional tests in an if statement.
The in operator
The in operator is used with lists, strings and other data structures. Here is an example of the in operator:
k = [1, 3, 5, 7] # A list of 4 items if 3 in k: print("List contains a 3") if 4 in k: print("List contains a 4")
This is hopefully self-explanatory. The list
k contains a 3, so the first if statement passes, and the message List contains a 3 is printed. The list does not contain a 4 so the second message is not printed.
in works with strings too. It can be used to check if a string contains a particular character, but it can also be used to check if a string contains a group of characters (a substring):
s = "Hello, world!" if "ello" in s: print("List contains ello") if "wrld" in s: print("List contains wrld")
Here, the first if statement passes because
s contains the sequence of characters ello. But the second if statement fails because
s does not contain the substring wrld. It contains those characters, but not in the exact order. So only the first message is printed.
There is also a not in operator that is true if the value is not in the list or string.
if, else and elif
Now we will write a simple program where the user can type in the name of an animal, and the program will tell them what noise the animal makes. Here is a simple start:
animal = input("Which animal?") if animal=="cat": print("A cat says meow")
The input statement will prompt you to enter a type of animal. If that animal happens to be a cat (the only animal the program knows about) it will print an answer.
The problem with our program is that, if you type in 'dog' (or anything other than 'cat'), you will get no response at all. We can fix that with an else clause:
animal = input("Which animal?") if animal=="cat": print("A cat says meow") else: print("I don't know that animal")
In this case, if the test is true (the animal is a cat), the body of the if statement runs – the first print statement executes.
If the test is false (the animal is not a cat) the body of the else statement runs – the second print statement executes, telling the user I don't know that animal.
With if/else, the program always executes one case or the other (but never both) – the if clause if the test is true, the else clause if it is false.
Now, what if we wanted to add some more animals to our program? We want to extend our if statement so that, instead of having just two cases (cat or not known) we can have dogs, and horses, and anything else we might want. That is where elif comes in.
elif is short for else-if. What it allows you to do is add another test (essentially another if clause) and another action is that case is true.
Here is the code:
animal = input("Which animal?") if animal=="cat": print("A cat says meow") elif animal=="dog": print("A dog says woof") elif animal=="horse": print("A horse says neigh") else: print("I don't know that animal")
What does this code do? Well, it works through the tests, one by one, until it finds a test that passes, and then executes that code. It will always execute exactly one case – either the animal that matches or the else clause if there are no matches.
Notice that the final clause is an else clause. That is a catch-all clause, if none of the other conditions is true, the else clause will run.
In natural language, you could think of this as if it's a cat, do the cat thing, else if it's a dog, do the dog thing, else if it's a horse, do the horse thing, else unknown.
Join the PythonInformer Newsletter
Sign up using this form to receive an email when new content is added:
2d arrays abstract data type alignment and angle animation arc array arrays bar chart bar style behavioural pattern bezier curve built-in function callable object chain circle classes clipping close closure cmyk colour combinations comparison operator comprehension context context manager conversion count creational pattern data science data types decorator design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate fill filter font font style for loop formula function function composition function plot functools game development generativepy tutorial generator geometry gif global variable gradient greyscale higher order function hsl html image image processing imagesurface immutable object in operator index inner function input installing iter iterable iterator itertools join l system lambda function len lerp line line plot line style linear gradient linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map marker style matplotlib monad mutability named parameter numeric python numpy object open operator optimisation optional parameter or pandas partial application path pattern permutations pie chart pil pillow polygon pong positional parameter print product programming paradigms programming techniques pure function python standard library radial gradient range recipes rectangle recursion reduce regular polygon repeat rgb rotation roundrect scaling scatter plot scipy sector segment sequence setup shape singleton slice slicing sound spirograph sprite square str stream string stroke structural pattern subpath symmetric encryption template text text metrics tinkerbell fractal transform translation transparency triangle truthy value tuple turtle unpacking user space vectorisation webserver website while loop zip zip_longest