Not able to use this while loop properly - python

Trying to sum up all the negative numbers in a list using while loop.
given_list_02 = [9, 8, 5, 3, -1, -2, -3, -6]
total3 = 0
i = 0
while True:
if given_list_02[i] >= 0:
i+= 1
else:
total3+= given_list_02[i]
i+= 1

Using for loop (recommended)
In python, for loops are based on iterators. As such, we are able to iterate over the values in the list rather than using a while True loop that updates an index i. This also makes sure we don't get an index out of bound error when i becomes larger than the length of the list:
given_list_02 = [9, 8, 5, 3, -1, -2, -3, -6]
numOfNegatives = 0
for num in given_list_02:
if num < 0:
numOfNegatives+=num
print(numOfNegatives)
Using while loop (not recommended)
You need a terminating condition for the while loop. If we think about what while True does, it will infinitely increment the i variable. So what would happen when i becomes 9? At this point, given_list_02[i] does not exist as given_list_02 only has 8 elements. This is why we need to stop iterating i once it hits 8:
given_list_02 = [9, 8, 5, 3, -1, -2, -3, -6]
total3 = 0
i = 0
while i < len(given_list_02):
if given_list_02[i] >= 0:
i+= 1
else:
total3+= given_list_02[i]
i+= 1
print(total3)

Your while loop does not have a break condition, so it will run indefinitely. As you are accessing list elements, you will access an index out out range at some point.
Try something like this
given_list_02 = [9, 8, 5, 3, -1, -2, -3, -6]
total3 = 0
for e in given_list_02:
if e < 0:
total3 += e
Since you commented, that you want to use a while loop for training purposes, try this:
given_list_02 = [9, 8, 5, 3, -1, -2, -3, -6]
total3 = 0
i = 0
while i < len(given_list_02):
if given_list_02[i] < 0:
total3 += given_list_02[i]
i += 1
Keep in mind though, that you really should prefer the for loop in this case.

Related

Python loops with break/continue

Given a set of integers numbers = [10, 0, 11, 5, 3, 0, 6, 0, 2, 0, 6, 9] containing at least two zeros. Print the sum of numbers from the given set located between the last two zeros (if the last zeros are in a row, then print 0).
My attempt:
numbers = [10, 0, 11, 5, 3, 0, 6, 0, 2, 0, 6, 9]
index_of_first_zero = 0
i = 0
while i < len(numbers):
if numbers[i] == 0:
index_first_zero = 1
break
i += 1
index_of_last_zero = len(numbers) - 1
i = len(numbers) - 1
while i >= 0:
if numbers[i] == 0:
index_of_last_zero = i
break
i -= 1
summa = 0
while i in range(index_of_first_zero+1, index_of_last_zero):
summa += numbers[i]
print("Summa =", summa)
But unput is Summa = 0
Can you help me please?
It's much easier to reverse the list and look for the first two zeros.
>>> numbers = [10, 0, 11, 5, 3, 0, 6, 0, 2, 0, 6, 9]
>>> numbers_rev = reversed(numbers)
>>> sum_ = 0
>>>
>>> for x in numbers_rev:
... if x == 0:
... break
>>>
>>> for x in numbers_rev:
... if x == 0:
... break
... sum_ += x
>>>
>>> sum_
2
Alternative:
numbers = [10, 0, 11, 5, 3, 0, 6, 0, 2, 5, 6, 0, 6, 9]
numbers_rev = numbers[::-1]
sum_ = 0
for x in numbers_rev[numbers_rev.index(0)+1:]:
if x == 0:
break
sum_ += x
This should do the trick...
a = [10, 0, 11, 5, 3, 0, 6, 0, 2, 0, 6, 9]
i1 = a[::-1].index(0)
i2 = a[::-1].index(0,i1+1)
print("Summa =",sum(a[len(a)-i2:len(a)-i1]))
I hope this makes it clear :)
#take your original list
numbers = [10, 0, 11, 5, 3, 0, 6, 0, 2, 0, 6, 9]
#reverse the list
numbes = numbers.reverse()
#make clear that the first zero has not been encountered
encountered_zero = False
#set the temporary sum to 0
cur_sum = 0
#for every number in your list
for number in numbers:
#if it's a zero, and you haven't passed any yet
if number == 0 and not encountered_zero:
#mark it
encountered_zero = True
#skip the rest of the iteration
continue
#if you have already encountered a zero
if encountered_zero == True:
#add every number to the sum
cur_sum += number
#if you encounter another zero
if encountered_zero == True and number == 0:
#break out of the loop, you're done
break
#here you have your answer
summa = cur_sum
print("Summa =", summa)
There are a few mistakes in your program...
One mistake in your program is that in the final part you're telling the script: "While the variable i is in the iterator range do [...]"
However, you should put a for loop there, not a while, changing it to:
summa = 0
for i in range(index_of_first_zero+1, index_of_last_zero):
summa += numbers[i]
print("Summa = ", summa)
Now that part of the program should work properly, because i in the for loop will be replaced with the values in the range iterator.
Instead, with the while, i takes index_of_last_zero as value, so it will never be in the range iterator.
However, the second error is a logical one: you have to sum the numbers between the last two zeros, not between the first and the last one, so the best thing to do is to reverse the list as other users already answered, so the entire program has to change:
original_list = [10, 0, 11, 5, 3, 0, 6, 0, 2, 0, 6, 9]
reversed_list = reversed(original_list)
my_sum = 0
for num in reversed_list:
if num == 0:
# it breaks here because it found the first zero,
# and then it will continue the cycle from the next element
break
# Now it won't loop again from the beginning, but from where it broke before.
for num in reversed_list:
if num == 0:
break
my_sum += num
print(my_sum) # -> 2
This program will work, thanks to #timgeb, and works with reversed() which is a built-in function that returns an Iterator object.
Here will be clarified to you what is an Iterator and how to work with it.
Anyway, I'll put here another solution that won't use that function.
original_list = [10, 0, 11, 5, 3, 0, 6, 0, 2, 0, 6, 9]
reversed_list = [] # we'll create it manually
my_sum = 0
# let's create here the reversed_list
for i in range(len(original_list) - 1, 0, -1):
reversed_list.append(original_list[i])
while i < len(reversed_list):
if reversed_list[i] == 0:
# it breaks here because it found the first zero,
# and we store the index of the first zero.
index_first_zero = i
break
i += 1
# Now it won't loop again from the beginning, but from where it broke before.
for i in range(index_first_zero, len(reversed_list)):
if reversed_list[i] == 0:
break
my_sum += reversed_list[i]
print(my_sum) # -> 2

Range() returning different output than "list" in "for" loop

I'm a beginner trying to understand why I get a different output when I use the range function. If I use (len(arr)) the output: 5 0 3 vs using arr the output: 3 2 1
arr = [-4, 3, -9, 0, 4, 1]
def plusMinus(arr):
count_pos = 0
count_neg = 0
count_zero = 0
for i in range(len(arr)):
if i>0:
count_pos += 1
if i<0:
count_neg += 1
else:
count_zero += 1
print(count_pos)
print(count_neg)
print(count_zero)
Comparing that version to not using range() and just arr:
def plusMinus(arr):
count_pos = 0
count_neg = 0
count_zero = 0
for i in arr:
if i>0:
count_pos += 1
if i<0:
count_neg += 1
else:
count_zero += 1
print(count_pos)
print(count_neg)
print(count_zero)
Thanks everyone for your explanations!
So it turns out I wasn't aware that range() calls upon indexing, and if my function doesn't also index the variable ( arr[i] ) then I am just looping through and making calculations off the index numbers [0,1,2,3,4,5] instead of the actual values[-4, 3, -9, 0, 4, 1]. Good to know! Thanks everyone!
These are two different by meaning things
range(len(arr))
will return a list from 0 to len(arr) - 1
List is iterable so you can iterate over its elements
The default iteration construction is for loop
for i in <iterable>:
So in the first example you are iterating over
[0, 1, 2, 3, 4, 5]
which was created by range()
In the second example you are iterating over
[-4, 3, -9, 0, 4, 1]
That is the difference

Why won't my code sum the value of the negative numbers in the list?

given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
total7 = 0
i = 0
while i <= len(given_list3) and given_list3[i] <= 0:
total7 += givenlist3[i]
i += 1
print(total7)
The code is producing a result of 0, and I want to to result in: -2 + -3 + -5 + -7 = -17
You can use comprehension:
given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
output = sum(x for x in given_list3 if x < 0)
print(output) # -17
In your current code, you are exiting the while loop even before the first iteration, because the second condition given_list3[i] <= 0 is false (since the first item 7 is greater than 0). If you want a working version, try the following. (Also you need to use i < len(...), not i <= len(...).)
given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
total7 = 0
i = 0
while i < len(given_list3):
if given_list3[i] <= 0:
total7 += given_list3[i]
i += 1
print(total7) # -17
A while loop stops when the condition is false. So your loop stops when it gets to the first positive value. Since the first element of the list is positive, the loop doesn't do anything.
The negative condition should be if inside the loop.
Also, list indexes go to len(list)-1, so the length condition should be <, not <=.
while i < len(given_list3):
if given_list3[i] <= 0:
total7 += given_list3[i]
i += 1
You should get out of the habit of looping over list indexes. Use for-in:
for item in given_list3:
if item <= 0:
total7 += item
You never iterate through your while loop.
On the first iteration i is 0 and the while-loop checks it's condition:
white 0 <= len(given_list3) and given_list3[i] < = 0:
...
given_list3[i] when i is 0 is given_list3[0] which is 7. 7 is not less than or equal to 0. The whole condition fails and the while loop is done.
The statements in the while-loop get executet as long as the condition is true. In your sample the condition is already false the first time it is checked and the statements in the while-loop never get executed.

While loop : Stuck at one point

How to find the sum of all the negative numbers in this list
I created below code:
given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
total7 = 0
i = 0
while i < len(given_list3) and given_list3[i] < 0:
total7 += given_list3[i]
i += 1
print(total7)
Not sure why it is giving me a zero. Please help.
Problem in given code is that it stops running as soon as it starts. This is because of condition:
while i < len(given_list3) and given_list3[i] < 0
When it checks first element for condition even though i < len(given_list3) is true but given_list3[i] < 0 is false. As there is and between both conditions so it means both conditions have to be true for loop to run else it will exit right away.
Additionally, If in your code calculation is only happening in one line then you can do:
while i < len(given_list3):
total7 += ((given_list3[i] < 0)*given_list3[i])
i += 1
In code (given_list3[i] < 0) becomes 1 (True) if i is less than 0 otherwise it becomes 0 (false). So all positive components are eliminated.
You should replace your while loop with this
while i < len(given_list3):
if given_list3[i]<0:
total7 += given_list3[i]
i += 1
print(total7)
In your code, i=0. When you do given_list[i] it means given_list[0] as i=0. But the first number is 7. And according to the loop, it should iterate only if i is less than length of the list and given_list[i] is less than 0. But 7 is greater than 0 and it just skips the loop. Hence you get the output as 0
You can use list comprehension
given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
sum([i for i in given_list3 if i<0])
-17
I am glad that i am able to answer this question,
So answer of this question is-
Better you use for loop and give if condition inside for loop.
I hope this will help you for your question.

Use a while loop to find sum of list until negative number or end of list appears

I am supposed to use a while loop to find the sum of a list until it reaches a negative number or until it reaches the end of the list. Here are example lists:
v = [ 10, 12, 3, -5, 5, 6 ]
v = [ 0, 10, 3, 6, 5, 1 ]
The output total sum for both lists should be 25. Here is my code:
result = 0
i = 0
for num in v:
while num >= 0:
result += num
i += 1
print(result)
For both of the lists, my output is just a blank infinite loop. The code I provided was the code I thought made the most sense.
You should use OR conditions with a single while loop, like so:
v = [10, 12, 3, -5, 5, 6]
v = [0, 10, 3, 6, 5, 1]
result = 0
i = 0
# while the sum is still at or above 0 and the list isn't out of bounds
while v[i] >= 0 and i < len(v):
num = v[i]
result += num
i += 1
print(result)
This enables you to avoid break statements, which are generally bad coding practice.
Use if, not while, and break to terminate the loop early. Also, you do not need i.
v = [ 10, 12, 3, -5, 5, 6 ]
# v = [ 0, 10, 3, 6, 5, 1 ]
sum_non_negatives = 0
for num in v:
if num < 0:
break
sum_non_negatives += num
print(sum_non_negatives)
Using only while (not for):
result = 0
i = 0
while i<len(v) and v[i] >= 0:
result += v[i]
i += 1
print(result)

Categories