why does python print not working after return?

Question:

Why does print statement not run after I return in recursion in Python?

arr=['zero','one','two','three','four','five','six','seven','eight','nine']
def numToWord(num):
    if num==0:
        return
    
    dig=num%10
    num=num//10
    #print(arr[dig],end=" ")
    return numToWord(num)
    print(arr[dig],end=" ")
    
numToWord(345)
Asked By: VVarun

||

Answers:

**A return is a value that a function returns to the calling script or function when it completes its task.
So here return takes as a termination of this function. That's why it will not jump to next line.**
Answered By: Kazi Akib Javed

How return works is it ends the function and everything after it will not run. I would change your code to this:

arr=['zero','one','two','three','four','five','six','seven','eight','nine']

def numToWord(num):
    if num == 0:
        return

    dig = num % 10
    num = num // 10
    return dig,num

dig,num=numToWord(345)
print(arr[dig],end=" ")
Answered By: Flow
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.