The moment you figure out how to work with conditionals in Python you will find yourself in the perfect spot to start making more complex programs.
“To be, or not to be?” - Hamlet, Shakespeare
The answer to this question is a Boolean and what if I told you there was a way to make the computer do different things based on its value?
You had better know how to assign different values to a variable because here you will see values act as the most basic (or primitive) data elements necessary to form not only variables, but any expressions.
Conditionals in Python: The If statement
Let’s start off by taking a look at one of the conditionals in Python – the “if” statement. What you can use it for is intuitive, but it is very important to learn the syntax. Think of the following: if 5 = 15 / 3, then print “Hooray!”
In Python and many other programming languages, the equality sign means ‘to assign a value’. However, when using conditionals, we often want to check if a condition is satisfied. In this case, we use a double equality sign(==). Moreover, 5 is a number, not a variable, so assigning a value to it would be meaningless.
The proper syntax when employing conditionals:
It is crucial to place a colon. The colon will tell the computer what to do if the condition we just wrote has been satisfied.
To achieve good legibility, we usually write the print statement on a new line. Please, remember that in Python it should be indented; otherwise, we will run into an error.
It worked this time but will it work if we check for 5 being equal to 18 divided by 3? It is not supposed to since 5 differs from 6.
We got nothing because we have not told the machine what to do if the provided condition is not satisfied.
How Does It Work?
The graph could help you imagine the process of the conditionals in Python. Before it displays the outcome of the operation, the machine follows these logical steps.
If the conditional code is not to be executed because the “if”-condition is not true, our program will directly lead us to some other output or, as it is in our case, to nothing.
After any of the two situations, the machine will go to the next black point and will progress from there on.
Let’s try with an inequality sign, which can be written with an exclamation mark and an equals sign (!=).
Is 5 different from 3 times 6? Yes, it is.
Hence, we have “Hooray!” as an output.
How to Create More Options?
What if we want to exhaust all the possibilities? Well, we can write two ‘if’ statements. So, let’s declare a variable called x and assign the value of 1 to it. We can ask the computer to display “Case 1” if x is greater than 3, and “Case 2” if it is less than or equal to 3.
One way we can go about creating more options is to write two “if” statements one after another.
However, there is a shorter and better way to express ourselves here.
Conditionals in Python: The Else Statement
In the second part, instead of saying “If x is smaller than or equal to 3”, we could directly write “else” and insert a colon.
The other conditional in Python, “else”, will tell the computer to execute the successive command in all other cases. In our little program, that would mean “in all cases when x is not greater than 3”. That translates into “when x is less than or equal to 3”. So, to cover all the possibilities, we don’t need two “if” statements, but rather one “if” and one “else”.
How Does It Work?
The picture below adds up to the one we saw earlier. Instead of leading to no output, if the condition is false, we will get to an “else” code.
In our case, this is the command print “Case 2”. Regardless whether the initial condition is satisfied, we will get to the end point, so the computer has concluded the entire operation and is ready to execute a new one.
There are two things that you should keep in mind when writing conditionals in Python:
- Don’t fall into the trap of organizing your code on a whim. There is a strict manner to do that, and indentation plays a key role again. Should you put the “else” keyword, just underneath the first “print” word, nothing will happen.
- Remember to place the “if” and the “else” keywords on the same vertical line!
Blocks of Code
It feels like a good time for you to become familiar with the notion of blocks of code. The “if”-statement, meaning the condition plus the relevant “print()” command, form the first block of code. The entire “else”-statement forms another block of code on its own.
In a long sheet with a lot of code, you’ll have many blocks. And larger programs are constructed on a block by block basis.
Boolean Values
In the beginning, we started with the famous Shakespearean dilemma. That was no coincidence. Quite often, conditionals work based on Boolean logic. Let’s illustrate this with an example. First, we could change the value of x to be equal to 2. Then, we can create the following “if-else” construction: – if the value of the x variable is greater than 4, print out “Correct”. In all other cases, print “Incorrect”.
So, which is the Boolean element we have in this computational logic?
Basically, after we insert our “if”-statement, the computer will attach a Boolean value to it. Depending on the value of its outcome, “True” or “False”, it will produce one of the suggested outputs, “Correct” or “Incorrect”.
If the first statement is “True”, that is, if x is greater than 4, the machine will print the corresponding statement “Correct”. Else, which means if the statement “x is greater than 4” is untrue, or more precisely “False”, the statement “Incorrect” will be printed.
From a certain perspective, everything in a computer system is Boolean, comprising sequences of 0s and 1s, “False” and “True”. This is why we are paying attention to the Boolean value. It helps us understand general computational logic and the way conditionals work in Python.
What to Look out for When Working with Conditionals in Python?
To sum up, you may use conditionals in Python freely, but you must make sure that you are complying with the Pythonic syntax and you should be careful when it comes to:
- Python indentation because it is a big peculiarity of the language.
- Boolean logic (as a general programming concept).
After having learned how to work with conditionals, don’t think twice before jumping into the depths of the decision making in Python by using elif.
***
If you’re enthusiastic about boosting your Python knowledge, check out our super practical tutorials!
Test what you've learned with these exercises:
Conditional Statements Exercise
Python ELSE Statement Exercise
Need help with learning Python? Check out our detailed Introduction to Python course.