ewe
ewe

Reputation: 159

while loop requires a specific order to work?

When I use the following code I get a correct answer of 28.

#want to find sum of only the positive numbers in the list
#numbers = [1,3,9,10,-1,-2,-9,-5]
numbers = [4,6,2,7,9]
numbers.sort(reverse = True) # sets to greatest to smallest numbers
total = 0
_index = 0
#while numbers[_index] > 0 and _index < len(numbers):
while _index < len(numbers) and numbers[_index] > 0:
    total += numbers[_index]
    _index += 1
print(total)

When I try the following code I get "IndexError: list index out of range", I only changed the while loop. Why does one condition have to be first, does it not check each one before running this loop?

#want to find sum of only the positive numbers in the list
#numbers = [1,3,9,10,-1,-2,-9,-5]
numbers = [4,6,2,7,9]
numbers.sort(reverse = True) # sets to greatest to smallest numbers
total = 0
_index = 0
while numbers[_index] > 0 and _index < len(numbers):
#while _index < len(numbers) and numbers[_index] > 0:
    total += numbers[_index]
    _index += 1
print(total)

Upvotes: 5

Views: 60

Answers (3)

eraul
eraul

Reputation: 63

When the _index = 5, use the first way, _index < len(numbers) will return false, this judgment statement will end directly because of short-circuit evaluation. The other expression will not be executed.

But if you use second way, the first expression will raise IndexError exception, because numbers[5] is out of range. For more knowledge about short circuit evaluation, please refer to:Boolean Operations

Upvotes: 1

Mandera
Mandera

Reputation: 2992

It's pretty simple if you think about it, this applies to if statements as well. If you have the following scenario:

if False and True:

It doesn't even check the second part, it doesn't matter, because the first part isn't True.

Same applies to

if True or False:

The second part doesn't matter because the code inside the if statement is going to run regardless.

Upvotes: 2

bhristov
bhristov

Reputation: 3187

The answer to your question is called short-circuit evaluation.

If the first part of a compound conditional AND statement evaluates to False then the second is not being evaluated in the case of an AND conditional.

If the conditional is an OR conditional, if the first part evaluates to True then there is no point in checking the second part of the conditional.

In your case with the indexes. If the length is already past the length of the array and you check to see that this is the case first - you will never go out of bounds:

# here if the index is out of bounds we won't procede to access the elements
while _index < len(numbers) and numbers[_index] > 0:

If you first try to access the element in the array you risk going out of bounds.

Upvotes: 3

Related Questions