Newbie - Trying to Help a Friend

Steven D'Aprano steve+comp.lang.python at
Wed Nov 20 01:17:23 CET 2013

On Tue, 19 Nov 2013 10:40:18 -0800, bradleybooth12345 wrote:

> Hi,
> A Friend is doing maths in University and has had some coursework to do
> with python.
> The question is
> "Write a program that calculates how many positive integers less than N
> are not divisible by 2,3 or 5. The user should be prompted to supply the
> Number N. Demonstrate your program output when the input N is your
> student id. (13006517)

Have your friend start by writing down how she or he would solve this 
problem by hand. I'll get you started by solving the problem for 7.

Positive integers less than 23 are 1, 2, 3, 4, 5, 6. So let's start 
checking them for divisors:

- 1 is not divisible by 2, 3 or 5, so we count one number.
- 2 is divisible by 2, but not by 3 or 5, so we count two numbers.
- 3 is not divisible by 2, so we count three numbers.
- 4 is divisible by 2, but not 3 or 5, so we count four numbers
- 5 is not divisible by 2, so we count five numbers.
- 6 is divisible by 2 and 3, but not by 5, so we count six numbers.

And the answer is: 6.

Now that you know what you yourself would do to solve this problem, the 
next step is to write it in terms that a computer can understand. A few 

1) You can check divisibility by using the % operator, which returns the 
remainder after division. So 36 % 6 gives 0, which means that 36 is 
divisible by 6. 37 % 6 gives 1, which means 37 is not divisible by 6.

2) You can use "for i in range(1, N)" to generate the positive integers 
less than N.

3) You can use the "or" operator to efficiently check multiple 
conditions. For example, this line of code:

if (a % 2) or (a > 16):

checks whether a number a is either an odd number or larger than sixteen, 
and if so runs the indented block of code following (not shown).

4) You can prompt the user for a value using the input (Python 3) or 
raw_input (Python 2) function. For example, using Python 2:

result = raw_input("Enter a number between 3 and 12: ")

lets the user type in anything in response. That result will be a string, 
to convert it to a number:

result = int(result)

5) You can create a variable and initialise it to some value like this:

count = 0

creates a variable called "count", set to the value 0. You can then add 
one to it like this:

count = count + 1

or if you prefer:

count += 1

Either way adds one to count.

I expect that the above should be enough to get your friend started and 
possibly even finished. If she/he gets stuck, come back with some code 
and specific questions.

Good luck!


More information about the Python-list mailing list