-2

Here my codes:

v = [1, 2, 3, 4, 5, 7]

def con(v, i):
    if i == len(v) : return print("ok")
    con(v, i + 1)

print(con(v, 1))

heres the output:

ok
None

Does anyone know how i can solve?

salex
  • 77
  • 3

4 Answers4

2
  1. print returns None and you are returning prints result
  2. you forgot to return on line 5, it should be return con(v, i + 1) or else the function will return None
szdytom
  • 76
  • 5
1

Your code prints that because the result of this code is print(print("ok")) and a call to print returns None. You need to return something other than print("ok").

Ryan Laursen
  • 617
  • 4
  • 18
  • even if I remove the print the result doesn't change – salex Feb 28 '21 at 10:01
  • that's because you need to return something other than `print("ok")`, like the results of the recursion. szdytom's answer addresses what you want probably. – Ryan Laursen Feb 28 '21 at 10:02
0

Just call con(v,1). No need to use print(con(v,1))

Ram
  • 4,724
  • 2
  • 14
  • 22
0

I understand your question that you want to recursively obtain the length of the vector / go to the end of the vector. You need to get the result from the inner most recursion loop back to the outer most. Thus you need to return the result of the inner ones:

v = [1, 2, 3, 4, 5, 7]
def con(v, i):
    if i == len(v):
        print("ok")
        return i
    return(con(v, i + 1))

print("Length of vector is: ",con(v, 1))

that will give:

ok
Length of vector is:  6
planetmaker
  • 5,884
  • 3
  • 28
  • 37