Exercise
Absolute Magnitude
Objective
Develop a Python program to calculate (and display) the absolute value of a number x: if the number is positive, its absolute value is exactly the number x; if it's negative, its absolute value is -x.
Do it in two different ways in the same program: using "if" and using the "conditional operator" (?).
Example Python Exercise
Show Python Code
Using "if"
# Prompt the user to enter a number
x = float(input("Please enter a number: "))
# Calculate the absolute value using if
if x >= 0:
abs_value_if = x
else:
abs_value_if = -x
# Display the absolute value using if
print(f"Absolute value using if: {abs_value_if}")
#Using Conditional Operator
# Prompt the user to enter a number
x = float(input("Please enter a number: "))
# Calculate the absolute value using the conditional operator
abs_value_conditional = x if x >= 0 else -x
# Display the absolute value using the conditional operator
print(f"Absolute value using the conditional operator: {abs_value_conditional}")
Output
Please enter a number: -5
Absolute value using if: 5.0
Absolute value using the conditional operator: 5.0
Share this Python Exercise