Given two numbers, the task is to add them and display their sum. For Example:
Input: a = 5, b = 7
Output: 12
Let's explore different methods to add two numbers in Python.
Using + Operator
The + operator performs arithmetic addition between two numbers and returns their sum. It is commonly used to add numeric values directly.
a = 15
b = 12
res = a + b
print(res)
Output
27
Using sum() Function
The sum() function adds all values present in an iterable like a list or tuple and returns the total sum.
nums = [10, 5]
print(sum(nums))
Output
15
Using operator.add()
The operator module provides the add() function, which performs addition between two values similar to the + operator.
import operator
print(operator.add(10, 5))
Output
15
Explanation: operator.add() takes two numbers as arguments and returns their sum.
Using math.fsum()
The fsum() function from the math module is used for precise floating-point addition. It helps reduce rounding errors while adding decimal values.
import math
nums = [0.1, 0.2]
print(math.fsum(nums))
Output
0.30000000000000004
Explanation: math.fsum() accurately adds floating-point values present in the list.