Python | Ranges and loops exercise | A program to print out the first N primes

This exercise is provided to allow potential course delegates to choose the correct Wise Owl Microsoft training course, and may not be reproduced in whole or in part in any format without the prior written consent of Wise Owl.

Software ==> Python  (28 exercises)
Version ==> Latest version
Topic ==> Ranges and loops  (4 exercises)
Level ==> Average difficulty
Subject ==> Python training

You need a minimum screen resolution of about 700 pixels width to see our exercises. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

A prime number is one which is only divisible by itself and 1 (so 23 is a prime, but 21 isn't because it's also divisible by 3 and 7).

Create a program call Prime numbers to loop over the integers from 2 up to 100:

Start of program

The start of your program - more is to be added shortly!


Within this loop, set the value of a variable called if_prime to be True.

This is a common programming tactic: you assume something is true for each time round a loop, then try to disprove it.

Within the outer loop, write an inner loop which loops from 2 up to a number 1 less than the outer loop integer.  For each time round the inner loop, if the inner loop integer exactly divides the outer loop one then the outer one wasn't a prime and your program should:

  • Set the value of if_prime to be False; and
  • Break out of the loop.

If your program finishes the inner loop with the value of if_prime still set to True it must mean that the outer loop integer was prime, so print out its value. 

Here's what you should get when you run the final program:

Prime numbers

The start of one of the most important sequences in maths.


When you're happy your program is working you could change it to loop over the first 1000, then 10,000, then 100, 000 numbers ... !

You can unzip this file to see the answers to this exercise, although please remember this is for your personal use only.
This page has 0 threads Add post