Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A terrible way to calculate the absolute value of a number in Python.
# A terrible way to calculate the absolute value of any integer with no reliance on complex computer math!
# Do not do this.
# Usage:
# >>> abs(10)
# 10
# >>> abs(-10)
# 10
# >>> abs(10.2)
# 10.2
# >>> abs(-10.2)
# 10.2
def abs(x):
if isinstance(x, int) and (x_s := str(x)).startswith('-'):
return int(x_s[1:])
elif isinstance(x, float) and (x_s := str(x)).startswith('-'):
return float(x_s[1:])
else:
return x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment