In this post, we will learn how to subtract two numbers using Python Programming language.
We will be using multiple ways to perform this task. The different methods are as follows:
- Using Standard Method
- Using User Input
- Using functions
So, without further ado, let’s begin this tutorial.
Python Program to Subtract Two Numbers
# Python Program to Subtract Two Numbers a = 27 b = 10 # Subtracting two numbers diff = a - b # Displaying output print("The subtraction of {0} and {1} is: {2}" .format(a, b, diff))
Output
The subtraction of 27 and 10 is: 17
Python Program to Subtract Two Numbers With User Input
# Python Program to Subtract Two Numbers With User Input x = int(input("Enter first integer: ")) y = int(input("Enter second integer: ")) # Subtracting diff = x - y # Displaying output print("The subtraction of {0} and {1} is: {2}" .format(x, y, diff))
Output
Enter first integer: 15
Enter second integer: 8
The subtraction of 15 and 8 is: 7
How Does This Program Work ?
x = int(input("Enter first integer: ")) y = int(input("Enter second integer: "))
The user is asked to enter two integers. The value of these two integers will get stored in the x and y named variables.
# Subtracting diff = x - y
We subtract two numbers with the help of the minus (-) operator.
# Displaying output print("The subtraction of {0} and {1} is: {2}" .format(x, y, diff))
Finally, the result of the subtraction is displayed on the screen using print() function.
Python Program to Subtract Two Numbers Using Functions
# Python Program to Subtract Two Numbers Using Functions def subtract(x, y): return x - y # Asking for input num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) diff = subtract(num1, num2) # Displaying output print("The subtraction of {0} and {1} is: {2}" .format(num1, num2, diff))
Output
Enter first number: 48
Enter second number: 21
The subtraction of 48 and 21 is: 27
Conclusion
I hope after going through this post, you understand how to subtract two numbers using Python Programming language.
If you have any doubts regarding the program, feel free to contact us in the comment section. We will be delighted to assist you.
Also Read: