In this article, we will learn about python program to subtract integer and float numbers with examples.
Getting Started
The task is to subtract integer and float numbers in python. For example,
If a = 10 and b = 1.2, then output is 10 – 1.2 = 8.8
We can do so in multiple ways –
- Simple Approach
- Using User Input
- Using User Input(Command Line Arguments)
- Using Lambda
- Using Function
Simple Approach
Using – operator, we can write python program to subtract integer and float numbers. For example,
b1 = 28 b2 = 4.32 result = b1 - b2 # Subtract using - operator print("Result:", result)
Output:
Result: 23.68
Using User Input
Instead of static input, we can take input from user using input() method in python. After that, we can type cast using float() and int() method and subtract using – operator. For example,
b1 = float(input("Enter a float number")) b2 = int(input("Enter an integer")) result = b1 - b2 print("{0} - {1} is {2}" .format(b1, b2, result))
Output:
Enter a float number 12 Enter an integer 2 12.0 - 2 is 10.0
Using User Input (Command Line Arguments)
Using sys.argv present in sys module in python, we can accept user input from command line arguments. For example,
-
Method 1
import sys b1, b2 = sys.argv[1:3] print("Result:", float(b1) - int(b2))
Output:
Result: -2.6799999999999997
-
Method 2
We can accept more than two input from command line argument as –
import sys b1, b2 = sys.argv[1:] print("Result:", float(b1) - int(b2))
Output:
Result: -2.6799999999999997
Using Lambda
If we want to write logic to subtract integer and float numbers in lambda function, we can do so as shown below –
if __name__ == "__main__" : b1 = 7.68 b2 = 2 # Subtract integer and float numbers subtract_IntFloat = lambda b1, b2 : b1 - b2 print("Result:", subtract_IntFloat(b1, b2))
Output:
Result: 5.68
Using Function
If we want to wrap logic to subtract integer and float number in a function, we can do so as shown below –
def subtractIntFloat(b1, b2): return b1 - b2 print("Result:", subtractIntFloat(41.5, 2))
Output:
Result: 39.5
That’s how we can write python program to subtract integer and float numbers with examples.
Reference: Subtraction
Learn about more python examples at – https://tutorialwing.com/python-tutorial/