Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Calculate the Absolute Value (Solution)

Avatar image for Andrii Dashchakovskyi

Andrii Dashchakovskyi on May 14, 2025

The output of print in the solution is a bit different from what is asked in the exercise.

Avatar image for Bartosz Zaczyński

Bartosz Zaczyński RP Team on May 14, 2025

@Andrii Dashchakovskyi Sharp eye! The formatting wasn’t the point of this exercise, but you’re right. One way to keep the original value the user has supplied could be the following:

>>> user_input = input("Enter a number: ")
Enter a number: -10

>>> print(f"The absolute value of {user_input} is {abs(float(user_input))}")
The absolute value of -10 is 10.0

This will produce the expected output for the given input. Alternatively, you could format both numbers to your liking explicitly:

>>> num = float(input("Enter a number: "))
Enter a number: -10

>>> print(f"The absolute value of {num:.3f} is {abs(num):.3f}")
The absolute value of -10.000 is 10.000

All approaches are valid. It just depends on whether you want to preserve the raw input or apply consistent number formatting.

Become a Member to join the conversation.