Search code examples
pythonpython-3.xfunctionabsolute-value

recreation of absolute value finder not working as intended


I have scripted a code that gives the absolute value of any number here is the code:

def absolute(num):
    numb = str(num)
    numb.replace("-","")
    numb = int(numb)
    return numb

When used it gives an output of the same integer:

>>> absolute(-12)
-12

When I did the function step by step I found out that there is the problem in int function where the string "12" gets converted into -12

I know other methods of making this but if you can explain why this happens and that would be better as I can understand what happens.

Thanks!


Solution

  • Here you don't assign .replace return value back to the variable:

    def absolute(num):
        numb = str(num)
        numb = numb.replace("-","")
        numb = int(numb)
        return numb
    

    In short:

    def absolute(num):
        return int(str(num).replace('-',''))
    

    And one bizarre thing, don't you know about abs() LOL?

    abs(-12)