It is more usual to use the for loops without using the range(). That kind of loop (in Python) is usually used for looping through the element values, not through the index values. When you need the index, use the enumerate() function to get both the index and the element value, like this (but you do not need it in the case):
...
for i, e in enumerate(nums):
do something with index and/or the element
...
The problem is not related to index values. This way, the for / while solutions differ only in accessing the elements of the array. You need to use indexing with the while but you do not need indexing with the for.
The problem with your while approach also is that you cannot simply skip the index after the value 13 because the next element can also contain 13. You need to store the value of the previous element and to use it for decision whether the current value should be added to the sum or not. It will be the same in both for and while solutions. Something like this:
last = 0 # init; whatever value different from 13
sum = 0
the chosen kind of loop:
e ... # current element from nums
if e != 13 bool_operator_here last != 13: # think about what boolean operator is
add the element to the sum
remember e as the last element for the next loop
sum contains the result
[Edited later] OK, you gave up. Here is the code that solves the problem:
def sumNot13for(nums):
last = 0 # init; whatever value different from 13
sum = 0
for e in nums:
if e != 13 and last != 13:
sum += e # add the element to the sum
last = e # remember e as the last element for the next loop
return sum
def sumNot13while(nums):
last = 0 # init; whatever value different from 13
sum = 0
i = 0 # lists/arrays use zero-based indexing
while i < len(nums):
e = nums[i] # get the current element
if e != 13 and last != 13:
sum += e # add the element to the sum
last = e # remember e as the last element for the next loop
i += 1 # the index must be incremented for the next loop
return sum
if __name__ == '__main__':
print(sumNot13for([2, 5, 7, 13, 15, 19]))
print(sumNot13while([2, 5, 7, 13, 15, 19]))
print(sumNot13for([2, 5, 7, 13, 13, 13, 13, 13, 13, 15, 19]))
print(sumNot13while([2, 5, 7, 13, 13, 13, 13, 13, 13, 15, 19]))
range()should not be used in thewhileloop. Therange()produces a sequence of numbers. Thewhileexpects a boolean predicate. Thewhileas shown here will not pass a single loop, because the first value produced by therangeis zero. This is interpreted as the False value. Also, thereturnis indented incorrectly.