Find Absolute Value in Python
See what Python abs normally hides by writing the sign decision yourself. This beginner lesson keeps the original input and explains a signed-zero wrinkle.
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)
Sample Output
Absolute value of -7.0 is 7.0
Negating -7.0 produces 7.0 while num stays -7.0 for the message.
In this one
- Interpret absolute value as distance
- Negate only negative values
- Keep original input separate from its result
How it works
- 1
Convert the response into a float.
- 2
Assign -num for num < 0, otherwise assign num unchanged.
- 3
Print both num and abs_value.
Edge cases
Positive number
Enter 7.
The else branch leaves the value at 7.0.
Signed zero
Enter -0.0.
The test is false and the stored result can still display as -0.0.
What's going on
Absolute value is distance from zero. A negative input needs its sign flipped; a non-negative input can stay as it is. The builtin abs does this for you, but the if version shows the decision.
For -7, num < 0 is True and -num becomes 7.0. For 7, the else branch copies the value unchanged. The original num remains available for the output label because the result uses a separate name, abs_value.
Signed floating-point zero is a wrinkle. -0.0 < 0 is False, so this manual code keeps -0.0 and can print that sign. abs(-0.0) instead returns 0.0. Both compare equal numerically, but their text can differ. The example is about finite real inputs, not complex-number magnitudes.
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.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does -num do when num is -7?
Pick an answer to check it.
Question 2
Does assigning abs_value change num?
Pick an answer to check it.
Questions people ask
What does -num do when num is -7?
It negates the negative value, producing positive 7.0.
Does assigning abs_value change num?
No. It binds a separate name for the result and keeps num for the label.
What builtin is normally used?
abs is the usual function for an absolute value; this version exposes the branch.