Home > Blockchain >  How to use varied funtions?
How to use varied funtions?

Time:10-04

l am trying to make a program that runs with the following definitions but when l run the code l get recursion error and l was wondering if someone could help on why this happens and how to fix it.

If x >= 0, then absolute value to x identical with x

If x < 0, then absolute value - x absolute value shall always be positive)

def absol(x):
    if x>=0:
          return absol(x)
    elif x<=0:
        return absol(x)

    
print("absolute value to 5 is", absol(5))
print("absolute value to -3 is", absol(-3))
print("absolute value to 0 is", absol(0))
absol()

CodePudding user response:

Your code does not reflect the logic you outline in prose. You could do the following if you insist on a recursive approach:

def absol(x):
    if x >= 0:     # base case is needed
        return x   # that does NOT recurse
    else:
        return absol(-x)  
        # argument must be different for the recursive call
        # so you can reach the base case eventually
  • Related