This program below is supposed to count the number of occurrences of x in a list. Can not identify the error in the code
def count_x( items, x ): if items==: return 0 first = items.pop(0) if first == x: return 1 + count_x(items, x)
There are better ways to do this, but it’s worth addressing why your code is throwing an error.
You don’t have a case for when the item popped is not equal to your search item. This causes the function to return a None. Since it is working recursively, it tries to compute
int + None, which leads to an error.
The other issue is that you are modifying the list with the function, which you may not want. For example:
def count_x( items, x ): print(items) if items==: return 0 first = items.pop(0) if first == x: return 1 + count_x(items, x) else: return count_x(items, x) items = [1, 2, 1, 1] print(count_x(items, 1)) print(items)
items will become an empty list after you run the function.