Python Program to Subtract Two Float Numbers

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

Getting Started

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

If a = 10.1 and b = 1.1, then output is 10.1 – 1.1 = 9.0

We can do so in multiple ways –

Simple Approach

Two float numbers in python can be subtracted using operator. For example,

 
c1 = 28.23
c2 = 4.32

result = c1 - c2  # Subtract using - operator
print("Result:", result)

Output:

 
Result: 23.91

Using User Input

If we don’t want to take static input, we can accept input from user when program is run using input() method. After that, subtract them using operator. For example,

 
c1 = float(input("Enter a float number"))
c2 = float(input("Enter another float number"))

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

Output:

 
Enter a float number
12.32
Enter another float number
23.12
12.32 - 23.12 is -10.8

Using User Input (Command Line Arguments)

Command line inputs can be taken using sys.argv present in sys module in python. After that, we can convert them into float numbers using float() method. Then, subtract them using operator.

  • Method 1

     
    import sys
    c1, c2 = sys.argv[1:3]
    print("Result:", float(c1) - float(c2))
    

    Output:

     
    Result: 9.989999999999998
    

    Run above code with command line arguments as 12.12 and 2.13.

  • Method 2

     
    import sys
    c1, c2 = sys.argv[1:]
    print("Result:", float(c1) - float(c2))
    

    Output:

     
    Result: 9.989999999999998
    

    Run above code with command line arguments as 12.12 and 2.13.

Using Lambda

Below is the lambda function that can be used to subtract two float numbers in python –

 
if __name__ == "__main__" :
    c1 = 7.68
    c2 = 2.41
 
    # Subtract two float numbers
    subtract_Float = lambda c1, c2 : c1 - c2
    print("Result:", subtract_Float(c1, c2))

Output:

 
Result: 5.27

Using Function

Below is a function that contains logic to subtract two float numbers –

 
def subtractFloat(b1, b2):
    return b1 - b2

print("Result:", subtractFloat(41.52, 2.17))

Output:

 
Result: 39.35

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

Reference: Subtraction

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

Leave a Reply