GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Home
  • Why Practice Python?
  • Why Chilis?
  • Resources for learners
  • Exercises
  • Blog
  • About

This view

  • Original page
  • New address

GeezerVison is showing www.practicepython.org — 11 Check Primality Functions Solutions

Practice Python

  • follow us in feedly
  • Atom feed XML
Follow @practice_python

Beginner Python exercises

  • Home
  • Why Practice Python?
  • Why Chilis?
  • Resources for learners
  • Exercises
  • Blog
  • About

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?

Buy me a coffee

Share the fun!

« Previous exercise Next exercise »

Explore Yubico
Explore Yubico
comments powered by Disqus
Copyright Michele Pratusevich, 2014-2022.
Advertising disclosure
You are visitor 01402809 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.