Find Absolute Value in Python
If it's negative, flip the sign. abs() exists; this is the if version.
BeginnerBasic Python ProgramsExample 18 of 25
find-absolute-value.py
1# Program to find the absolute value of a number23num = float(input("Enter a number: "))45if num < 0:6 abs_value = -num7else:8 abs_value = num910print("Absolute value of", num, "is", abs_value)
Output
Enter a number: -7 Absolute value of -7.0 is 7.0
In this one
- if n < 0: n = -n
- abs() is the same thing, shorter
What's going on
Distance from zero. Negative → multiply by -1. Otherwise leave it.
abs(-7) is the builtin. This page writes the if so you see there is no magic.
-0.0 is a weird float. Python still prints it as absolute 0.0 here. Don't chase that.
After this program
If the idea is still fuzzy, read Day 1: Introduction to Python in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 basic python programs, or see every topic on Python exercises.