Check whether an element is there or not in a list using recursion in python
Question:
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))
Answers:
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
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))
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