How to Add Two Numbers in Python (original) (raw)

Last Updated : 07 Mar, 2025

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.

Python `

a = 15 b = 12

Adding two numbers

res = a + b print(res)

`

Table of Content

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.

Python `

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.

Python `

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)

`

**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.

Python `

res = lambda a, b: a + b print(res(10, 5))

`

**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.

Python `

import operator print(operator.add(10, 5))

`

**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.

Python `

print(sum([10, 5]))

`

**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: