Search code examples
pythonrecursionunbound

local variable referenced before assignment in recursion


My program isn't working.

It is meant to be

  • you have an array and a code
  • if the code is 0 then you have to add up the numbers
  • if it is anything else then you have to multiply them
  • I want it to use recursion but when you get to less then 5 numbers then I don't use more recursion, I just want do it normally

This is the problem I get

    the_rest = sum_or_product(code, array[1:])
UnboundLocalError: local variable 'sum_or_product' referenced before assignment

This is the program

def sum_or_product(code, array):

    if code == 0:
        do = 'SUM'
    else:
        do = 'PRODUCT'

    # THIS IS WITH THE RECURSION

    if len(array) >= 5:
        this_one = array[0]
        the_rest = sum_or_product(code, array[1:])
        if do == 'SUM':
            return this_one + the_rest
        if do == 'PRODUCT':
            return this_one * the_rest

    # THIS IS WITHOUT THE RECURSION

    if do == 'SUM':
        start = 0

    if do == 'PRODUCT':
        start = 1

    sofar = start

    for i in array:
        if do == 'SUM':
            total = sofar + i
            sofar = total
        if do == 'PRODUCT':
            product = sofar * i
            sofar = product
    sum_or_product = sofar

    return sum_or_product


print(sum_or_product(1, [1,2,3,4,5,6,7,8,9,10]))

It should mutiply all the numbers from 1 to 10. But it just gives an error.


Solution

  • In order to return a value from a function, you just

    return <value>
    

    instead of assigning the value to the function.

    So in order to fix your code you just need to replace

        sum_or_product = sofar
    
        return sum_or_product
    

    with

        return sofar
    

    As a side note, instead of using obscure conventions like '0 is SUM, 1 is PRODUCT', use constants, e.g.:

    OP_SUM=0
    OP_PRODUCT=1
    
    def sum_or_product(operation, array):
    
    ...
    
        if operation == OP_SUM:
            ...
        elif operation == OP_PRODUCT:
            ...
    
    ...
    
    print(sum_or_product(OP_SUM, [2, 3]))