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?
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?
print
returns None
and you are returning print
s resultreturn con(v, i + 1)
or else the function will return None
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")
.
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