How To Subtract Two Numbers In Python?
Below, are the ways To Subtract Two Numbers In Python.
- Using Minus Operator (-)
- Using a Function
- Bitwise Subtraction
- Using Lambda Function
Subtract Two Numbers Using Minus Operator (-)
In this example, below code subtracts `num2` from `num1` using the minus operator and prints the result, showcasing a basic subtraction operation in Python.
Python3
# Example num1 = 10 num2 = 5 result = num1 - num2 print ( "Subtraction using the Minus Operator:" , result) |
Subtraction using the Minus Operator: 5
Subtract Two Numbers Using Function
In this example, below code defines a function `subtract_numbers` to perform subtraction between two parameters (`num1` and `num2`), and then demonstrates its usage by subtracting `number2` from `number1`, displaying the result with a formatted print statement.
Python3
# Function to subtract two numbers def subtract_numbers(num1, num2): result = num1 - num2 return result # Example usage number1 = 40 number2 = 18 subtraction_result = subtract_numbers(number1, number2) print (f "Subtraction using Function: {subtraction_result}" ) |
Subtraction using Function: 22
Subtract Two Numbers Bitwise Subtraction
In this example, below code demonstrates subtraction by using bitwise operations: it complements `num2` with bitwise NOT (`~`), adds 1, and then adds the result to `num1`, showcasing an alternative method for subtraction in Python.
Python3
# Example num1 = 25 num2 = 12 result = num1 + ~num2 + 1 print ( "Subtraction using Bitwise Operation:" , result) |
Subtraction using Bitwise Operation: 13
Subtract Two Numbers Using Lambda Function
In this example, below code defines a lambda function `subtract` that subtracts `y` from `x`, and then applies it to subtract `num2` from `num1`, showcasing a concise way of performing subtraction using lambda functions in Python.
Python3
# Example subtract = lambda x, y: x - y num1 = 30 num2 = 15 result = subtract(num1, num2) print ( "Subtraction using Lambda Function:" , result) |
Subtraction using Lambda Function: 15
Conclusion
Subtracting two numbers in Python can be achieved through various methods, each with its own advantages and use cases. Whether you prefer the simplicity of the minus operator or the versatility of lambda functions, mastering these techniques will undoubtedly enhance your Python programming skills. Experiment with these methods to gain a deeper understanding of Python’s flexibility and power in performing basic arithmetic operations.
Subtract Two Numbers in Python
Python is a flexible and easy-to-learn programming language. It provides different ways to do basic math operations. In this article, we’ll look at how to subtract two numbers in Python. Whether you’re new to programming or have some experience, learning these methods will help you get better at using Python.