Hi I'm new to programming. I tried to use for loop and a nested while loop to calculate the sum of an arithmetic sequence on condition that the sum is no bigger than 100. I wrote the code below, but the output was 100 instead of the correct sum of the elements of the sequence (which should be 92).
# Arithmetic sequence
ele = 1
diff = 3
arithmetic_sequence = []
while ele < 60:
arithmetic_sequence.append(ele)
ele = diff
print(arithmetic_sequence)
#[output: [1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, 49, 52, 55, 58]]
# Sum of the arithmetic sequence -- the output is 100, very weird
sum_arithmetic = 0
for ele_f in arithmetic_sequence:
while sum_arithmetic < 100:
sum_arithmetic = ele_f
print(sum_arithmetic)
#[output: 100]
Could anyone help me check what went wrong in my code? Thank you in advance!
CodePudding user response:
You need not use a while loop inside the for, your code as of now keeps adding the same ele_f
until it reaches a sum less than 100, so basically it is adding 1
100 times which gives 100, after which the condition is no longer true for any other ele_f
in arithmetic_sequence
.
In other words, your for loop executes the while part only for the first element.
You need this (if
instead of while
and the condition is changed slightly)
sum_arithmetic = 0
for ele_f in arithmetic_sequence:
if (sum_arithmetic ele_f) < 100:
sum_arithmetic = ele_f
CodePudding user response:
Putting a nested while
loop in the for
loop is not doing that you think it is.
What you want to do is:
- Loop over the elements of the sequence, adding the current element at each iteration
- If the sum is greater than or equal to 100, stop there and keep the sum under 100
However what you are actually doing is:
- Looping over all the elements of the sequence
- At each iteration, adding the current element until the sum is 100
So all your code does is repeatedly add 1, and never add any of the other elements. (Because the sum is already 100, from all the 1s that you added.)
What you want is an if
statement inside the for
loop to check if it should continue:
sum_arithmetic = 0
for ele_f in arithmetic_sequence:
if sum_arithmetic ele_f >= 100:
break
sum_arithmetic = ele_f
In this code, the break
will end the for
loop early if the if
statement ever runs.