Home > Blockchain >  I can't get python to return the values of the function
I can't get python to return the values of the function

Time:06-05

I can't get python to return the values of the function I have tried joining the function variables into one and I test the values separately with python print and they work but in the test it only returns the value none.

this is the code.

import codecs
import os
import re

a = str(r"'c:\videos\my video.mp4'")
b = a.replace('\\','/')
real_direct=b.replace(' ','')
max_caract = int(len(real_direct)-1)  
def dividir(i) :
   if real_direct[i]=='/' :
       print(real_direct[i])
       direct = real_direct[2 : i 1] 
       file = real_direct[i 1 : max_caract]
       #print(direct)
       #print(file)
       return (direct, file)
   else: 
        dividir(i-1)

print(dividir(max_caract))

CodePudding user response:

At the very least, you need a return in the else branch to return the value from the recursive call. Otherwise it gets thrown away and the function implicitly returns None.

CodePudding user response:

The problem here is that you are calling a function recursively, and its inner-most function call is the only thing that returns anything. Everything else, including the dividir() that is being printed, return nothing. return dividir(i-1) in the else solves it.

#!/usr/bin/env python3

import codecs
import os
import re
from pathlib import Path

a = str(r"'c:\videos\my video.mp4'")
b = a.replace("\\", "/")
real_direct = b.replace(" ", "")
max_caract = int(len(real_direct) - 1)


def dividir(i):
    print('starting dividir function')
    if real_direct[i] == "/":
        print(f'{real_direct[i]=}')
        direct = real_direct[2 : i   1]
        file = real_direct[i   1 : max_caract]
        print(f'{direct=}')
        print(f'{file=}')
        return (direct, file)
    else:
        print('doing else')
        return dividir(i - 1)



print(dividir(max_caract))
$ ./codecs.py
starting dividir function
doing else
starting dividir function
doing else
starting dividir function
doing else
starting dividir function
doing else
starting dividir function
doing else
starting dividir function
doing else
starting dividir function
doing else
starting dividir function
doing else
starting dividir function
doing else
starting dividir function
doing else
starting dividir function
doing else
starting dividir function
doing else
starting dividir function
real_direct[i]='/'
direct=':/videos/'
file='myvideo.mp4'
(':/videos/', 'myvideo.mp4')

CodePudding user response:

You neither have a return nor have a print statement in the else part of your code. You can do it similarly to how you’ve implemented the return in the if part, or add a print statement like you’ve done earlier as well if you just wish to see the output on the screen

  • Related