im doing this exercise basically to add the first 2 integers in a list in python, but my script shows it runs the for loop twice before it iterates to the next integer in a list.
my code is below, i added a print statement so i can see how it iterates the FOR loop inside a WHILE loop.
def add2(nums):
count = 0
ans = 0
while count <= 2:
count += 1
print(f'count: {count}')
for x in nums:
ans += x
print(f'ans: {ans}')
HOwever if i run my code, i get this result. Why is it adding the value of ans twice before it goes to the next iteration? add2([2,3,5]) count: 1 ans: 2 ans: 5 ans: 10 count: 2 ans: 12 ans: 15 ans: 20 count: 3 ans: 22 ans: 25 ans: 30
forloop is inside thewhileloop. Theforsolves itself first, then go back to thewhile. Since your input is a list (iterable), it adds all the value inside the list as many times as yourcountlimit + 1 (because it starts from 0)