Skip to content

Python difference between two numbers | Example code

  • by

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 the 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)

Output: 50

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)

Output: 22

Get the difference between 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)

Output:

Python difference between two numbers

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)

Output: 400

Do comment if you have any doubts or suggestions on this Python number topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading