Python ELSE Statement: Exercise

Join over 2 million students who advanced their careers with 365 Data Science. Learn from instructors who have worked at Meta, Spotify, Google, IKEA, Netflix, and Coca-Cola and master Python, SQL, Excel, machine learning, data analysis, AI fundamentals, and more.

Start for Free
Martin Ganchev 24 Apr 2023 1 min read

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

python solution image, else statement exercise

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

if x%2!=0:

or

if x%2==1:

we simply type ELSE.

else:
 
    print("Odd")

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 in our ELIF Statement Exercise. Enroll in our Introduction to Python course for more useful exercises.

Martin Ganchev

Instructor at 365 Data Science

Martin holds an MSc degree in Economic and Social Sciences from Bocconi University. His diverse academic and research experience combined with his friendly and explanatory approach to teaching have made him one of the most beloved instructors on our team. Some of the courses he has authored include: SQL, SQL + Tableau, SQL+Tableau+Python, Introduction to Python, Introduction to Jupyter, to name a few.

Top