简体   繁体   中英

How to print numbers from 0 to 100 that are divisible by 3 and also 5?

I am a newbie to programing and i am doing python related exercises and i ran into this problem, where i have to print all the numbers divisible by 3 and also 5.

I know it is somehow related to the for loop with range but i cant figure it out.

I tried looking for solutions but those are out of my league i don't understand them.

for number in range (0, 100, 3):
    j = number / 5
    print (j)

i tried it like this but i get decimals for answer

You should try the modulus '%', which returns the decimal part (remainder) of the quotient.

for i in range(100): # Numbers between 0 and 100
    if i % 3 == 0 and i % 5 == 0:
        # If i is divisible by 3 and i is also divisible by 5 then print it
        print(i)

One optimization, number divisible by 3 and 5 must end with 0 or 5 , so we can iterate with step=5 and check only if number is divisible by 3:

print([n for n in range(0, 100, 5) if not n % 3])

Prints:

[0, 15, 30, 45, 60, 75, 90]

EDIT: 3 and 5 don't have common divisors, so it's enough to iterate with step 15:

print([n for n in range(0, 100, 15)])

Prints:

[0, 15, 30, 45, 60, 75, 90]

最简单的方法:

print([n for n in range(0, 100, 5) if not n % 3])
for number in range(100): if (number % 5 == 0) and (number % 3 == 0): print(number)

You need an if statement in that code and a couple small tweaks. I do not think you need the third argument in the for loop because that changes the increment. The %, or modulus is remainder division. So if remainder division returns 0 then we know that number is divisible by that number. We use an and statement to make sure that the number is divisible by 3 and 5

for number in range (0, 100):
    if (number % 15 == 0):
        print (number)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM