While loop : Stuck at one point - python

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.

Related

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.

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)

Not able to use this while loop properly

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.

Why doesn't my code on Jupyter produce an output

given_list = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
total = 0
i = 0
while i < len(given_list) and given_list[i] <= 0:
total += given_list[i]
i += 1
print(total)
I'm using Jupyter notebook and following the tutorials for python by CSdojo on youtube. I was wondering why when I run my code, the cell after it does not produce an output (total)?
The problem is given_list[i] <= 0.
First i = 0 then given_list[i] = 7
7 is not equal or less than 0, then True and False evaluates to False. That's why it doesn't show output.
In this case you don't have any problem with Jupyter or Python. Your problem was your logic. Please try hard in algorithm not syntax.

Categories