Search code examples
pythonpython-3.xpython-2.7jupyter-notebookspyder

How to handle negative inputs in a recursive product function?


because i found it hard to get

take a look:

def mult(a, b):
    if b == 0:
        return 0
    rest = mult(a, b - 1)
    value = a + rest
    return value

prod = int(input('Enter number: '))

print('The product of', prod, 'x', prod, 'is', mult(prod,prod))

Solution

  • Just start with

    def mult(a, b):
        if b<0: return -mult(a, -b)
    

    and continue with the code you have now (assuming the latter's indented properly -- right now it's something of a mess but I'll assume that's merely a formatting issue and the code will work if properly edited:-).