Python Program to Subtract Two Numbers

In this article, we will learn about python program to subtract two numbers with examples

Getting Started

The task is to subtract one number from another number in python. For example,

If a = 4 and b = 2, then output is 4 – 2 = 2.

We can do so in multiple ways –

Simple Approach

Using subtraction operator (i.e. operator), we can subtract two numbers in python as shown below:

 
x1 = 658
x2 = 64
 
result = x1 - x2  # Subtract using - operator
print("Result:", result)

Output:

 
Result: 594

Using User Input

We can also accept two numbers as input from user using input() method. Then, subtract those numbers using operator as shown below:

 
x1 = int(input("Enter a number"))
x2 = float(input("Enter another number"))

result = x1 - x2
print("{0} - {1} is {2}" .format(x1, x2, result))

Output:

 
Enter a number
23
Enter another number
12.1
23 - 12.1 is 10.9

Using User Input (Command Line Arguments)

sys.argv in sys module in python is used to take user input using command line arguments. Then, we can convert it to either float or int using float() and int() method. After that, we can use operator to subtract two numbers in python.

  • Method 1

    x1, x2 = sys.argv[1:3] reads two input from command line arguments and stores in variable x1 and x2.

     
    import sys
    x1, x2 = sys.argv[1:3]
    print("Result:", float(x1) - int(x2))
    

    Output:

     
    Result: 9.34
    

    Run above code with command line arguments as 12.34 and 3.

  • Method 2

    x1, x2 = sys.argv[1:] reads all input from command line and stores two values in x1 and x2.

     
    import sys
    x1, x2 = sys.argv[1:]
    print("Result:", float(x1) - int(x2))
    

    Output:

     
    Result: 9.34
    

    Run above code with command line arguments as 12.34 and 3.

Using Lambda

Here, we have defined a lambda function that can be used to subtract two numbers x1 and x2 using operator as shown below:

 
if __name__ == "__main__" :
    x1 = 76.82
    x2 = 2.49
 
    # Subtract two numbers
    subtract_twoNumbers = lambda x1, x2 : x1 - x2
    print("Result:", subtract_twoNumbers(x1, x2))

Output:

 
Result: 74.33

Using Function

subtractNumbers function contains logic to subtract two numbers in python as shown below –

 
def subtractNumbers(x1, x2):
    return x1 - x2
  
print("Result:", subtractNumbers(154, 228))

Output:

 
Result: -74

That’s how we can write python program to subtract two numbers with examples.

Reference: Subtraction

Learn about more python examples at – https://tutorialwing.com/python-tutorial/

Leave a Reply