Python Program to Subtract Two Integers With Examples

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

Getting Started

The task is to subtract two integers in python. For example,

If a = 12 and b = 3, then output is 12 – 3 = 9.

We can do so in multiple ways –

Simple Approach

Using operator, we can subtract two numbers in python as shown below –

 
a1 = 8
a2 = 4
 
result = a1 - a2  # Subtract using - operator
print("Result:", result)

Output:

 
Result: 4

Using User Input

We can take input from user using input() method. Then, type cast those input to integer using int() method.

 
a1 = int(input("Enter an integer"))
a2 = int(input("Enter another integer"))

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

Output:

 
Enter an integer
23
Enter another integer
12
23 - 12 is 11

Using User Input (Command Line Arguments)

We can accept input from command line arguments using sys.argv present in sys module in python. For example,

  • Method 1

    a1, a2 = sys.argv[1:3] accepts two values from command line arguments as store them in variable a1 and a2.

     
    import sys
    a1, a2 = sys.argv[1:3]
    print("Result:", int(a1) - int(a2))
    

    Output:

     
    Result: 57
    

    Run above code with command line arguments as 65 and 8.

  • Method 2

    If we don’t two restrict numbers of inputs to be read from command line arguments, we can omit second argument in sys.argv.

     
    import sys
    a1, a2 = sys.argv[1:]
    print("Result:", int(a1) - int(a2))
    

    Output:

     
    Result: 57
    

    Run above code with command line arguments as 65 and 8.

Using Lambda

Using lambda function, we can wrap logic to subtract two integers as shown below –

 
if __name__ == "__main__" :
    a1 = 768
    a2 = 24
 
    # Subtract two integers
    subtract_twoInt = lambda a1, a2 : a1 - a2
    print("Result:", subtract_twoInt(a1, a2))

Output:

 
Result: 744

Using Function

If we need to write a function to subtract two integers in python, we can do as below –

 
def subtractIntegers(a1, a2):
    return a1 - a2
  
print("Result:", subtractIntegers(15, 28))

Output:

 
Result: -13

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

Reference: Subtraction

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

Leave a Reply