0

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

1
  • I think you already answer your own question. It is because the for loop is inside the while loop. The for solves itself first, then go back to the while. Since your input is a list (iterable), it adds all the value inside the list as many times as your count limit + 1 (because it starts from 0) Commented Apr 27, 2021 at 4:56

2 Answers 2

1

You don't need to overcomplicate this. Just use slicing to return the first to elements of the list.

simpler code

listNums = [1,2,3,4]
print(float(listNums[0])+float(listNums[1]))

output

3.0

This is based on your explanation of the problem.


Now using your logic of solving this proble, I would consider removing the while loop altogether but keeping the for loop. Though keeping the plain for loop will not give us our desired output because it will find the sum of every number in the list. Instead we can cut the list of at two elements. The below code shows how to do that.

your logic code

def add2(nums):
    count = 0
    ans = 0
    for x in nums[:2]:
        ans += x
    print(f'ans: {ans}')
add2([1,2,3,4])

output

ans: 3
Sign up to request clarification or add additional context in comments.

2 Comments

great thanks guys for the suggestions, i was practicing using WHILE loop thus i have it in there.. yeah for this one i just have to make it simple for now
Give it a check if it helped.
0

It could be as simple as this:

ans=0
for i in range(len(nums)):
   ans+=nums[i]
   if i > 2:
      break

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.