Recommand · October 22, 2021 0

Python: How to choose specific number that is divisible by two numbers, but prints only the chosen number?

Sorry if my post is messy or hard to understand. I am just learning to code and to understand python. I have a homework where I am given n1 (random number from 0-10) and n2(from 30-45). My job is to print every number between n1 and n2 that is divisible by 2 but not by 3.

for x in range(n1,n2):
if x%2==0:
if x%3==0:

So this is my code now. I have tried it and it works, but it prints numbers like 6 and 12 that are divisible by 3. Hod do I fix it?

You just need to add an extra condition here:

for x in range(n1,n2):

   if x % 2 == 0 and x % 3 != 0:


Or to have the continue happen before the print such as:

for x in range(n1,n2):

   if x%3 == 0:

   if x%2 == 0:

What was happening was that you were printing first, and then checking the condition for divisibility by 3, which meant that even though you "skipped" the loop, you had already printed anyway.

You need to choose random number between 0-10 for n1 and 30-45 for n2. Import random module and use randint() to get random nos. Also, you can put both the conditions in same if statement. Your code:

import random
for i in range(n1,n2):
    if i%2==0 and i%3!=0: