Why in loop if the word return does not return anything?

def arithmetic(a,b):
    if a == 0 :
        return b
    else:
        arithmetic(a-1,b+a)

print(arithmetic(4,0))

2 answers

  • answered 2022-05-06 05:55 ewong

    The reason is you aren't returning the value from your else block.

    def arithmetic(a,b):
       if a == 0 :
          return b
       else:
          return arithmetic(a-1,b+a)
    
    print(arithmetic(4,0))
    

  • answered 2022-05-06 07:57 Jake Korman

    Here is a slick one-liner using a ternary if statement

    def arithmetic(a,b):
        return b if a == 0 else arithmetic(a-1,b+a)
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum