Ifs, Elifs, Elses
Table of Contents
When you're writing code in any programming language, you need to able to make decision based on the current state of the program. You'll want to be able to compare values to decide what path you want to take next. This is called logic.
Comparison Operators
To use logic in our program, we'll need to learn about the comparison operates that Python offers.
Equality Operator
The most basic comparison operators we have is the equality operator. This simply checks if two values are equivalent or not. If they are the same, the result will be true
, and if they are not equal, the result will be false
.
To use the equality operator, simply use two equal signs.
PYTHONnumber1 = 3
number2 = 3
print(number1 == number2)
BASHTrue
PYTHONnumber1 = 3
number2 = 6
print(number1 == number2)
BASHFalse
Inequality Operator
The inequality operator functions exactly like the equality operator we just saw but in reverse. If the two values are the same, it will result in false
, and if they are different, it will result in true
.
To use this operator, put an exclamation point in front of the equal sign, like so:
PYTHONnumber1 = 3
number2 = 3
print(number1 != number2)
BASHFalse
PYTHONnumber1 = 3
number2 = 6
print(number1 != number2)
BASHTrue
Greater Than and Less Than Operators
You can compare the values of two variables using the greater than and less than operators. Here is how to use them:
PYTHONnumber1 = 3
number2 = 6
print(number1 > number2) # greater than
BASHFalse
PYTHONnumber1 = 3
number2 = 6
print(number1 < number2) # less than
BASHTrue
Or Equal To Operators
In the case where you need to check if a value is either less than/greater than or equal to another value, Python also has an operator for that. It looks like a combination of the operators we saw before:
PYTHONprint(3 <= 5)
print(3 >= 5)
print(7 <= 8)
print(7 >= 9)
BASHTrue
False
True
False
Conditionals
Now that are able to compare two values, we can now do something with that result. Using conditionals we can now take different paths of code depending on if the value inside it is true
or false
.
If
Using the if keyword is very straightforward. If whatever you are checking is true
, then whatever is inside the next block of code will run.
Let's see an example of this:
PYTHONburritos = 6
if (burritos > 5):
print("You ordered too many burritos.")
BASHYou ordered too many burritos.
Now let's order a correct number of burritos and see what happens:
PYTHONburritos = 3
if (burritos > 5):
print("You ordered too many burritos.")
BASH
Nothing happened! The code block did not execute because the value of burrito
was not greater than 5
.
Else
You're probably thinking, well, I want to output something even if the correct number of burritos were ordered. Well, that's where else comes into play.
We can define another block of code to run whenever the if
conditional was false.
PYTHONburritos = 3
if (burritos > 5):
print("You ordered too many burritos.")
else:
print("You ordered a correct number of burritos!")
BASHYou ordered a correct number of burritos!
Else If
That's cool, but what if we wanted more than 2 code paths? That is where else if comes into play, or elif.
PYTHONburritos = 2
if (burritos > 5):
print("You ordered too many burritos.")
elif (burritos == 2):
print("You ordered the PERFECT number of burritos!")
else:
print("You ordered a correct number of burritos!")
BASHYou ordered the PERFECT number of burritos!
Since code executes from top to bottom, it will first do the first conditional. Since the value was not greater than 5
, it moved on the second conditional. Since the conditional there was true
, that code block was executed instead of the one below it.
Logical Operators
So far we've seen how logic works when we only have a single conditional to work with. Eventually, you will need to use multiple conditionals to finally make the decision about what path of code you want to take. When you want to use multiple conditionals at once, you use a logical operator.
And Operator
By using the and operator, the block of code will only execute if both sides of the operator are true:
PYTHONisHungry = True
foodAvailable = True
if (isHungry and foodAvailable):
print("Since I am hungry and there is food, I shall eat.")
BASHSince I am hungry and there is food, I shall eat.
Since in this case both variables were true
, the resulting code block was ran, and the print statement was displayed.
Or Operator
While using the and
operator, both conditionals needed to be true
, but with the or
operator, only a single one needs to be true
.
Consider this example:
PYTHONsunny = False
bored = True
if (sunny or bored):
print("Since it is either sunny outside or I'm bored, I will go play basketball.")
BASHSince it is either sunny outside or I'm bored, I will go play basketball.
Even though it is not sunny outside, because you are bored, you decided to play basketball anyway.
Not Operator
In our final logical operator, you can invert the results of a conditional entirely but using the not operator.
Let's look at an example:
PYTHONtemperature = 50
hot = temperature > 70
if not (hot):
print("Since it isn't hot, I will wear boots today!")
BASHSince it isn't hot, I will wear boots today!
If it isn't hot, which we defined as greater than 70
degrees, you will wear boots, which you did!
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Getting Started with Electron
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Getting Started with Vuex: Managing State in Vue