To find the positive difference between the two numbers we have subtracted the smaller number from the larger one in Python. Use an if statement to find which number is bigger.
Get difference between two numbers in Python
Simple example code.
num1 = 100 num2 = 50 if num1 > num2: diff = num1 - num2 else: diff = num2 - num1 print(diff)
Using abs() Function
The abs() method returns the absolute value of the given number. The difference is always positive.
num1 = 23 num2 = 45 diff = abs(num1 - num2) print(diff)
Get difference of user input numbers
Inputs are scanned using the input() function and stored in variables n1 and n2. Since input() returns a string, we convert the string to a number using the int() function.
n1 = int(input("Enter first number: ")) n2 = int(input("Enter second number: ")) if n1 > n2: diff = n1 - n2 else: diff = n2 - n1 print("The difference is:",diff)
How do I find the difference between two values without knowing which is larger?
Answer: abs(x-y) will do exactly what you’re looking for:
num1 = 100 num2 = 500 diff = abs(num1 - num2) print(diff)
Do comment if you have any doubts or suggestions on this Python number topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.