How to Add Two Numbers in Python
The task of adding two numbers in Python involves taking two input values and computing their sum using various techniques . For example, if a = 5 and b = 7 then after addition, the result will be 12.
Using the “+” Operator
+ operator is the simplest and most direct way to add two numbers . It performs standard arithmetic addition between two values and returns the result.
a = 15
b = 12
# Adding two numbers
res = a + b
print(res)
Output
27
Using user input
This method allows users to input numbers dynamically instead of hardcoding them. The input() function is used to take input from the user, which is then converted to a numerical format before performing addition.
# taking user input
a = input("First number: ")
b = input("Second number: ")
# converting input to float and adding
res = float(a) + float(b)
print(res)
Output
First number: 13.5
Second number: 1.54
15.04
Explanation: This code takes user input as strings, converts them to floats using float(), adds them and stores the sum in res.
Using Function
Functions help organize code into reusable blocks. By defining a function, we can call it multiple times with different values, making our program more structured and efficient.
# function to add two numbers
def add(a, b):
return a + b
# initializing numbers
a = 10
b = 5
# calling function
res = add(a,b)
print(res)
Output
15
Explanation: This code defines a function add(a, b) that returns the sum of a and b. It initializes a and b with values 10 and 5, calls the add() function with these values, stores the result in res.
Using Lambda Function
A lambda function is an anonymous, one-line function that can perform operations without defining a full function block. It is useful for short, simple calculations.
res = lambda a, b: a + b
print(res(10, 5))
Output
15
Explanation: lambda res that takes two arguments and returns their sum. The lambda function is then called with 10 and 5, returning 15 .
Using operator.add
operator module provides a functionally equivalent method to the + operator. This is useful when working with functional programming or reducing redundancy in complex operations.
import operator
print(operator.add(10, 5))
Output
15
Explanation: operator module, which provides functions for various arithmetic and logical operations. It then uses operator.add(10, 5), which performs addition like 10 + 5.
Using sum()
sum() function is commonly used to add multiple numbers in an iterable like lists or tuples. It provides a simple way to add elements without using loops or explicit operators.
print(sum([10, 5]))
Output
15
Explanation: This code uses the sum() function, which takes a list of numbers [10, 5] and returns their sum.
You can also check other operations:
- Minimum of two numbers in Python
- Find Maximum of two numbers in Python
- Python Program to Find the Gcd of Two Numbers
- Python program to add two binary numbers