Skip to Main Content
It looks like you're using Internet Explorer 11 or older. This website works best with modern browsers such as the latest versions of Chrome, Firefox, Safari, and Edge. If you continue with this browser, you may see unexpected results.

Python for Basic Data Analysis: 2.4 Functions - A Fun Exercise!

Get started on your learning journey towards data science using Python. Equip yourself with practical skills in Python programming for the purpose of basic data manipulation and analysis.

A Fun Exercise!

Let's create a function that will help us check if a number is prime.

A number is prime if the number is only divisible by 1 and itself.

This function will take in 1 argument, N, which is the number we want to check. Next, it will go through all the numbers from 1 to N and perform modulo checks.

Check your answer

Try it yourself before looking at the answers!
 

1. In your function, you can use a for-loop together with if-else conditions

2. Make use of % in python to find out the remainder. To find the remainder of 3 divided by 2, we write 3%2 

3. Take the given number and find the remainder when divided by all numbers from 1 to itself. Check whether the conditions for a prime number is met.

4. When a given number is divisible by another number, it is not prime. Use break to stop a for-loop without returning anything 

 

Take note on how the `else` lines up under for instead of if. We want the for loop to check all numbers 2 to N-1 before confirming that our number is prime. Should the else be alligned with if inside the for loop, we will be printing "is prime" before exhausting all possibilities.


break was introduced because once we have discovered that the number is not prime (i.e can be divided by a number that is not 1 and itself) we can stop checking and break out of the for loop.