Skip to content

Instantly share code, notes, and snippets.

@Sonictherocketman
Created August 23, 2021 22:46
Show Gist options
  • Save Sonictherocketman/e4afc0bc1776f0837d6abc7216d57a59 to your computer and use it in GitHub Desktop.
Save Sonictherocketman/e4afc0bc1776f0837d6abc7216d57a59 to your computer and use it in GitHub Desktop.
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