ELSE Statement Exercise:
Using a single IF statement, determine whether an integer x is even or odd.
The tutorial you may need: Learning How to Use Conditionals in Python
In a previous exercise of ours, we solve a similar problem with two IF statements. You can check that here if you wish.
It’s important to know that an IF statement goes hand in hand with an ELSE statement.
ELSE statements come in handy when we have many conditions that work, and we do not want to list them out one by one. In fact, what is great about the ELSE operator is that it does not require typing out a specific condition, yet still includes all scenarios where our IF statement was not satisfied.
Okay, on to the task at hand.
We start by introducing an IF statement that checks whether x is even.
Recall that we use the ‘%’ symbol to test divisibility. Per usual, we want to call the print-function when the IF condition is satisfied and display a message. Therefore, our code would be as follows:
if x % 2==0: print("Even")
Now, instead of typing another IF statement to account for x being odd, like
we simply type ELSE.
Due to x not being even, it can only be odd, so the else condition includes only that option. As you can see, we once again indent and call the print function on the next line and... voila!
By combining everything we’ve written so far, our final code will look like this:
if x % 2==0: print("Even") else: print("Odd")
That is all there is to it.
What if we have several independent conditions and then ‘all the rest’? Should we use several IF statements? Or is there a better way? Find out here - ELIF Statement Exercise