Home > database >  Element out of bounds printout as "None"
Element out of bounds printout as "None"

Time:11-09

The code below is an intent of printing out a list within the bounds of it. The list currently shows "None" after the last element (Yes, I know "None" in python is "Null" in C ), but I can't see why the while loop goes beyond the boundaries of the list when the "if" loop breaks it if it finds the element to be a "None"

def out_of_boud(lst):
    lst_length = int(len(lst))
    element = int(0)

    while (element >= 0 and element < lst_length):
        if element == None: break
        else:
            print(str(lst[element])   "\t"   str(element))
            element  =1

print(out_of_boud([10, 15, 20, 21, 22, 35]))
print(out_of_boud([10, 15, 20, 21]))

CodePudding user response:

The value None is not printed from your function. It's the value returned by your function (implicitly) and printed from the calling code (explicitly).

Explanation: since the function does not explicitly return a value, its return value is None. And because in your code you don't just call the function, but print its value (print(out_of_boud(...)), None is printed after the function body is executed.


Just as a comment, since your style seems to be shaped by other languages, there are much more succinct and Pythonic ways to achieve the things you are doing. This code is equivalent to your function (except for the None check):

for i, item in enumerate(lst):
    print(item, i, sep='\t')
  • Related