Read our blogs, tips and tutorials
Try our exercises or test your skills
Watch our tutorial videos or shorts
Take a self-paced course
Read our recent newsletters
License our courseware
Book expert consultancy
Buy our publications
Get help in using our site
493 attributed reviews in the last 3 years
Refreshingly small course sizes
Outstandingly good courseware
Whizzy online classrooms
Wise Owl trainers only (no freelancers)
Almost no cancellations
We have genuine integrity
We invoice after training
Review 30+ years of Wise Owl
View our top 100 clients
Search our website
We also send out useful tips in a monthly email newsletter ...
Software ==> | Python (34 exercises) |
Topic ==> | Ranges and loops (5 exercises) |
Level ==> | Harder than average |
Subject ==> | Python training |
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.
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). The aim of this program is to print out the first N primes:
N can be any number you choose (there are an infinite number of primes, so you won't run out ...).
Create a program call Prime numbers to loop over the integers from 2 up to 100.
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 you should test if the inner loop integer exactly divides the outer loop one:
Use syntax like this to see if when you divide one number by another you get a remainder of zero.
If the inner loop integer does exactly divide the outer loop one, this number wasn't a prime, so you should:
Set the value of if_prime to be False; then
Use the break command to break out of your 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.
Be very careful with your indentation! One feature of Python is that pressing Tab or Shift + Tab key to indent or unindent a line of code can completely change the way a program behaves.
When you're happy your program is working you could change it to loop over the first million integers, and have a well-earned coffee break ...
You can find other training resources for the subject of this exercise here:
Kingsmoor House
Railway Street
GLOSSOP
SK13 2AA
Landmark Offices
99 Bishopsgate
LONDON
EC2M 3XD
Holiday Inn
25 Aytoun Street
MANCHESTER
M1 3AE
© Wise Owl Business Solutions Ltd 2025. All Rights Reserved.