Python Conditional Statements: 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

Conditional Statements Exercise:

Create a function that counts the number of elements within a list that are greater than 30.

Here’s an example list you can use to test your work:

num = [1,4,62,78,32,23,90,24,2,34].

The tutorial you may need: Learning How to Use Conditionals in Python

python solution image, conditional statements

We start off the conditional statements exercise by defining a function that takes a list as its only parameter.

Next, we define a variable ‘count’ within the function to keep track of the number of elements greater than 30. Remember to initially assign 0 to the variable “count” since we don’t know if there are any 0 elements in the list.

Now that we have set our counter, we can go through the list. Using a ‘for’ loop, we go through each element one by one and check if it is greater than 30.

If an element satisfies our condition and the if-statement, we increase our ‘count’ variable by 1. If it doesn’t, we need not take any action, so no need to write any ELIF or ELSE statements.

Next, after the ‘for’ loop has concluded, we return the ‘count’ variable that kept track of all elements greater than 30.

def greater_than_30(numbers):
    count = 0
    for n in numbers:
        if n>30:
    return count

To make sure our work is correct we need to call the function.

Since it requires a parameter, we need to define a list of numbers outside the function. Remember to put the name of the list in parentheses when calling the function. You can create other lists or adjust the existing one to check your code. Don’t hesitate to try that, not only with integers but also floats!

Want to practice some more on lists? Take our Introduction to Python course.

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.