0

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!

POINT ONE
  • 33
  • 1
  • 7

2 Answers2

1

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)
Wasif
  • 14,755
  • 3
  • 14
  • 34
0
absolute = lambda x : int(str(x).replace('-',''))
absolute(-5)

I shortened the answer someone else gave you. Its a little slow when I time it but I'm sure it should work fine. :)