1

Here is the code which I wrote for checking whether an elements is there or not in a list using recursion in Python. According to the flow of the program, it should return True, but instead returns None. Please help in explaining where I went wrong. Thanks in advance.

def numCheck(list,num):
    if len(list) == 0:
        return
    if list[0] == num:
        return True
    else:
        numCheck(list[1:],num)
print(numCheck([1,2,3],2))
Vedant
  • 239
  • 2
  • 4
  • 13

1 Answers1

1

You need to return the result of the function call:

def numCheck(list,num):
  if len(list) == 0:
    return False
  if list[0] == num:
    return True
  return numCheck(list[1:],num)

print(numCheck([1,2,3],2))

Output:

True
Ajax1234
  • 66,333
  • 7
  • 57
  • 95