Pedro Vargas
Pedro Vargas

Reputation: 23

Different results trying to solve the same problem using for and while loops in python

Hi! I am new to coding and was trying to solve I tried to solve a problem that required me to sum all of the negative integers in a list using loops. I tried to solve the problem using both for and while loops but got different answers.

For Loop Code

glist3 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
total3=0
for i in glist3:
    if glist3[i]<0:
        total3+=glist3[i]
print(total3)

While Loop Code

glist4 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
i2=0
total4=0
while i2 < len(glist4):
    if glist4[i2] < 0:
        total4+=glist4[i2]
    i2+=1
print (total4)

The Result I got for the for loop is -12 (which is incorrect), but the while loop did give back the correct answer which is -13. Just wanted to ask for possible causes for this discrepancy. Thank you!

Upvotes: 2

Views: 116

Answers (3)

d_j1
d_j1

Reputation: 36

The error is in your for loop. You're saying for i in glist3, meaning that the variable i is taking the value of each number rather than incrementing by one yet you're indexing the list using it...

Replace glist3[i] with just i, so that you're adding the ACTUAL numbers rather than the numbers at thier index in the list, as seen below, and this will work...

glist3 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
total3=0
for i in glist3:
    if i<0:
        total3+=i
print(total3)

Or if you wanted to index... using a range will also work.

glist3 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
total3=0
for i in range(len(glist3)):
    if glist3[i]<0:
        total3+=glist3[i]
print(total3)

Both should now return -13 as intended.

Hope this helps, good luck!!

Upvotes: 1

Eleveres
Eleveres

Reputation: 47

While loops loop until the condition defined next to the "while" keyword is met.

For loops loop through iterators, for example: lists, dictionaries or even files.

So if you loop for example through a list of fruits like this:

fruits = ['banana', 'apple', 'mango', 'pear', 'pineapple']
for fruit in fruits:

The variable "fruit" will be equal to "banana" during the first loop, then "apple" the second and so on. "fruit" will not be equal to the index of the item. So in that example doing:

fruits = ['banana', 'apple', 'mango', 'pear', 'pineapple']
for fruit in fruits:
    print(fruits[fruit])

would result in an error since fruit is not an integer but a string.

If you wish to keep track of the index during a for loop you need to set a variable out of the for loop and then increment it in the loop.

Here's a working example of what you want to do using a for loop:

glist3 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
total3 = 0
for number in glist3:
    if number < 0:
        total3 += number
print(total3)

Upvotes: 0

Patrick Artner
Patrick Artner

Reputation: 51643

You while loop loops over idexes. The for loop over values. You use the values to index back into the list.

Fix:

glist3 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
total3=0
for i in glist3:      # these are the VALUES of the list, not indexes
    if i<0: 
        total3 += i   # simply add up the values
print(total3)         # -13 for the win

fixes it.

It is sheer luck that your numbers all work as indexes into your list as well - try adding a 99 and you'll get an IndexError.

Short version:

print( sum( i for i in [7,5,4,4,2,1,1,-2,-2,-4,-5] if i < 0) )

# or if you want to confuse people:
print( sum( i * (i<0) for i in [7,5,4,4,2,1,1,-2,-2,-4,-5]) )

Upvotes: 1

Related Questions