Ad

How Can I Convert To While Loop

- 1 answer

I wrote this code. It's like len() function.

def length_itr_for(list):
    total = 0
    for i in list:
        total += 1
    return total

print length_itr_for([1,2,3,4,5,6,7,8])

output is; 8. because in this list, there are 8 value. so len is of this list is 8.

but I don't know how can I write this code with while loop?

while list[i]: etc... I though a few things but I don't know what should I write it here.

edit: actually I tried this code too. but It's not good code. just tried and it didn't work.

def length_itr_whl(list):
    total = 0
    i = 0
    while list[i]:
        total = total + 1
        i = i + 1
    return total

print length_itr_whl([1,2,3,4,5])
Ad

Answer

If you really want to convert this code to a while-loop, you could always do something like this:

def length_itr_whl(list):
    total = 0
    i = 0
    while list[i:i+1]:
        total = total + 1
        i = i + 1
    return total

print length_itr_whl([1,2,3,4,5]) # prints 5
print length_itr_whl([]) # prints 0

This uses the list-slicing mechanism in Python and it does not require any try-block. When the indices are out of range the result will be [] (an empty list), which evaluates to False in Python.

However, why don't you just use the built-in len-function in Python?

Ad
source: stackoverflow.com
Ad