0

This code here:

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def evenlis(x, n = 0):  
    if n == len(x):
        return 
    if x[n] % 2 == 0:
        print(x[n], end = " ")
    evenlis(x, n + 1)
print(evenlis(arr))

prints all even numbers from the given array, but it also returns None at the end. How can I fix this?

There is the exit() function, which seems to remove that None, but it also ends the entire program, and I do not need that, because I have some code following this function.

Some clarification. The exit() function was used on the 4th line, which was later replaced by return.

  • 3
    You never `return` anything _except_ `None`, and `None` is returned unless you explicitly specify a different return value. – Charles Duffy Nov 20 '22 at 18:54
  • Also, note that in real world code (as opposed to academic exercises), functions that print data rather than returning or yielding results are generally frowned on. – Charles Duffy Nov 20 '22 at 18:55
  • @CharlesDuffy, this is an academic exercise (my homework) – Mihai Creciun Nov 20 '22 at 18:57
  • 1
    In general, just take out the `print()`. It prints the return value, and _that's_ the behavior you don't want. That is to say: Change `print(evenlis(arr))` to just `evenlis(arr)` and None will still be returned, but you'll no longer see it. – Charles Duffy Nov 20 '22 at 18:57
  • If your instructor _requires_ you to have the `print` there, that means it's incorrect to use `print()` inside the function and you should instead be constructing the function to return the desired value. – Charles Duffy Nov 20 '22 at 18:59

1 Answers1

0

You are getting the None portion since your code as it stands is requesting a value to print when your function is called within the print function. Instead of:

print(evenlis(arr))

You could just do the following.

evenlis(arr)
print()

Making that change provided the following terminal output.

@Dev:~/Python_Programs/Even$ python3 Even.py 
2 4 6 8 10 

Give that a try.

NoDakker
  • 3,390
  • 1
  • 10
  • 11
  • In [How to Answer](https://stackoverflow.com/help/how-to-answer), note the section _Answer Well-Asked Questions_, and the bullet point therein regarding questions that "have been asked and answered many times before". – Charles Duffy Nov 20 '22 at 19:09