Python programming and the use of for loops [closed]

a = range(1,20) 

Your program is creating a range of numbers between 1 and 19 (ranges go to one less than the max number you specify) like [1, 2, 3, 4, ..., 19]

total = 0

Your program is initializing the variable total to equal 0

for i in a:

You start looping through the range you made earlier, the first iteration i=1, the next i=2 and so on until i=19

if i % 3 == 0 or i % 5 == 0:

You are selecting only the data where the modulo of 5 or 3 is 0. For example:

3 % 3 == 0 (0 remainder)
4 % 3 == 1 (1 remainder)

Now altering your variable to a reasonable name (without spaces) that will actually utilize the variable we initialized above

total = total + i # alternatively written "total += i"

This says that every time the value i is evenly divisible by 3 or 5 we will add it to our total

print(total)

We show the final result after adding values. You incorrectly scripted your program to do this though so it only showed the largest value that was evenly divisible by 5 or 3 which is 18.

When scripted correctly:

a = range(1, 20)
total = 0
for i in a:
    if i % 3 == 0 or i % 5 == 0:
        total += i
print(total)

Outputs

78

Browse More Popular Posts

Leave a Comment