Question

I have a class file LinkedListADT.py and within that I have the class LinkedList. One method I have defined for this class is as follows:

def test(self, index=None):
    if index:
        print(str(index))
    else:
        print("Index not found")

Now, from my other file (not the class) I have defined the following function:

def test():
    tester = LinkedListADT.LinkedList()
    tester.test(0)

The result being printed is "Index not found" -- My question is, can 0 be passed as an optional input to a method or regular function?

I am quite new to Python and I'm assuming 0 is being interpreted as false. Whether or not this is the case, is there a workaround I can use?

Was it helpful?

Solution

As you guessed, 0 is considered as "falsey". The documentation lists other "falsey" values.

print bool(0)
# False

But you can check like this

def test(self, index=None):
    if index is not None:
        print(str(index))
    else:
        print("Index not found")

This program makes sure that the input is not None and if it is not, it is user provided (irrespective of its Truthiness).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top