Practice Python

Beginner Python exercises

16 April 2014

Check Primality Functions Solutions

Exercise 11

Ask the user for a number and determine whether the number is prime or not. (For those who have forgotten, a prime number is a number that has no divisors.). You can (and should!) use your answer to Exercise 4 to help you.

Sample solution

There are many ways of solving this problem, so here are a sample solutions:

This one is a different breakdown of functions to solve the problem. The strings between three ''' marks are comments in the code that describe what each function does.

And here is a solution without using functions. It is also a correct solution that accomplishes the given task, just without the use of functions.

This solution doesn’t use functions, but does use list comprehensions, which are always fun. Thanks to Carlos for this solution. The interesting thing here is the observation that when you want to check if a number is prime, all you need to do is check the numbers from 2 to the square root of the number. This is because the pair of numbers that are both the largest factors of the number are square root of x and square root of x. Otherwise, the number you are checking for can be found by finding the corresponding factor and checking it.

Another solution is a clean, short solution that uses list comprehensions.

Enjoying Practice Python?

Explore Yubico
Explore Yubico
comments powered by Disqus