I am trying to find the sum of numbers from the list which is squared.
x_sequence = [1, 2, 3, 4, 5]
total = 0
for i in x_sequence:
total = total (i * i)
if i % 5 == 0:
continue
print(total)
output: 30
this is first simple and it works correctly and prints out 30 which is square(1 2 3 4) but If I try to print only the final number out from the for loop it prints out 55 instead of 30 like this:
x_sequence = [1, 2, 3, 4, 5]
total = 0
for i in x_sequence:
total = total (i * i)
if i % 5 == 0:
continue
print(total)
output: 55
I wonder why does it do like this? I tried to replace total with only I like this: i = i (i * i)
but it gives me 30 if I remove 3, or 4 from the list too which I do not wish to.
I would like to achieve this: square all numbers from the list, find the sum of the squared list numbers, and if there is a squared number that gives 0 reminder after dividing 5 skip it
CodePudding user response:
The total value at the end of both code blocks is 55. The only difference is that at the last iteration, i % 5 equals 0 (continue), skipping the print of the last addition (25).
If you don't want to sum the square when reaching 5, move the skip condition before summing it to the total variable:
x_sequence = [1, 2, 3, 4, 5]
total = 0
for i in x_sequence:
if i % 5 == 0:
continue
total = total (i * i)
print(total)
> 30
CodePudding user response:
In the first code snippet you print inside the loop, but if the value is a multiple of 5
you won't print the total. Instead if the value of i
is a multiple of 5
then you continue the loop. Since the 5
is the last element in the list, the loop ends, and you won't print anything at all.
In the second code you print the total result once the loop is finished.
In both cases though, the total will include the added 25
(from 5 * 5
). The difference is that in the first code you don't print that value.
If you don't want multiples of 5
to be included in the total then you need to do the check before you do the multiplication and adding to total
:
if i % 5 == 0:
continue
total = total (i * i)
CodePudding user response:
You are adding squared value to the total before the if condition, so all numbers including the square of 5 will be added to the total, too. Try this:
x_sequence = [1, 2, 3, 4, 5]
total = 0
for i in x_sequence:
if i % 5 == 0:
continue
total = i * i
print(total)