The Wayback Machine - https://web.archive.org/web/20240926225517/https://www.geeksforgeeks.org/python-program-to-add-two-numbers/
Open In App

How to Add Two Numbers in Python – Easy Programs

Last Updated : 02 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Learn easy techniques and codes to add numbers in Python. Adding numbers in Python is a very easy task, and we have provided you 7 different ways to add numbers in Python.

Given two numbers num1 and num2. The task is to write a Python program to find the addition of these two numbers. 

Examples:

Input: num1 = 5, num2 = 3
Output: 8
Input: num1 = 13, num2 = 6
Output: 19

There are many methods to add two number in Python:

  • Using “+” operator
  • Defining a function that adds two number
  • Using operator.add method
  • Using lambda function
  • Using Recursive function

Each of these methods have been explained with their program below.

Add Two Numbers with “+” Operator

Here num1 and num2 are variables and we are going to add both variables with the + operator in Python.

Python
# Python3 program to add two numbers
num1 = 15
num2 = 12

# Adding two nos
sum = num1 + num2

# printing values
print("Sum of", num1, "and", num2 , "is", sum)

Output:

Sum of 15 and 12 is 27

We will now see Python programs to add two numbers without using + operator.

Add Two Numbers with User Input

In the below program to add two numbers in Python, the user is first asked to enter two numbers, and the input is scanned using the Python input() function and stored in the variables number1 and number2.

Then, the variable’s number1 and number2 are added using the arithmetic operator +, and the result is stored in the variable sum.

Python
# Python3 program to add two numbers

number1 = input("First number: ")
number2 = input("\nSecond number: ")

# Adding two numbers
# User might also enter float numbers
sum = float(number1) + float(number2)

# Display the sum
# will print value in float
print("The sum of {0} and {1} is {2}" .format(number1, 
                                            number2, sum))

Output:

First number: 13.5 Second number: 1.54
The sum of 13.5 and 1.54 is 15.04

Add Two Numbers in Python Using Function

This program show adding two numbers in Python using function. We can define a function that accepts two integers and returns their sum.

Python
#To define a function that take two integers 
# and return the sum of those two numbers
def add(a,b):
  return a+b

#initializing the variables
num1 = 10
num2 = 5

#function calling and store the result into sum_of_twonumbers
sum_of_twonumbers = add(num1,num2)

#To print the result
print("Sum of {0} and {1} is {2};" .format(num1,
                           num2, sum_of_twonumbers))

Output

Sum of 10 and 5 is 15;

Add Two Numbers Using operator.add() Method

Initialize two variables num1, and num2. Find sum using the operator.add() by passing num1, and num2 as arguments and assign to su. Display num1,num2 and su

Python
# Python3 program to add two numbers

num1 = 15
num2 = 12

# Adding two nos
import operator
su = operator.add(num1,num2)

# printing values
print("Sum of {0} and {1} is {2}" .format(num1,
                                       num2, su))

Output

Sum of 15 and 12 is 27

Read More: Operator Functions

Add Two Number Using Lambda Function

Here we are going to use Python Lambda function for addition of two number with Python

Python
# Define a lambda function to add two numbers
add_numbers = lambda x, y: x + y

# Take input from the user
num1 = 1
num2 = 2

# Call the lambda function to add the two numbers
result = add_numbers(num1, num2)

# Print the result
print("The sum of", num1, "and", num2, "is", result)

Output:

The sum of 1 and 2 is 3

Add Two Numbers Using Recursive Function

This code defines a recursive function to add two numbers by incrementing one number and decrementing the other. User inputs two numbers, and the sum is calculated and displayed.

Python
# Define a recursive function to add two numbers
def add_numbers_recursive(x, y):
    if y == 0:
        return x
    else:
        return add_numbers_recursive(x + 1, y - 1)

# Take input from the user
num1 = 1
num2 = 2

# Call the recursive function to add the two numbers
result = add_numbers_recursive(num1, num2)

# Print the result
print("The sum of", num1, "and", num2, "is", result)

Output:

The sum of 1 and 2 is 3

We have covered multiple programs to add two number in Python. You can use any one of the above method, to perform the task. Adding two numbers is a very easy task in Python, can be done using multiple functionalities.

This tutorial showed you the basic of addition of two numbers in Python. You can be creative and customize these programs to add multiple numbers in Python.

You can also check other operations:

How to Add Two Numbers in Python – FAQs

Can we add integers and floating-point numbers together in Python? 

Yes, Python allows you to add integers and floating-point numbers together seamlessly. When you perform arithmetic operations between integers and floats, Python automatically handles the conversion and performs the addition.

# Example:
a = 5 # Integer
b = 2.5 # Floating-point number

result = a + b
print(result) # Output: 7.5

Can we use bitwise operators to add numbers in Python?

Bitwise operators (&, |, ^, <<, >>, ~) perform operations at the bit level and are typically used for manipulating binary data rather than adding numbers in the conventional sense. While some bitwise operations might seem like addition in specific cases (such as | for bitwise OR), they are not used for general arithmetic addition.

# Example:
a = 5 # 101 in binary
b = 3 # 011 in binary

result = a | b # Bitwise OR operation
print(result) # Output: 7 (which is 111 in binary)

How to sum two numbers in a class in Python?

To sum two numbers within a class in Python, you can define a method that performs the addition.

class Calculator:
def add(self, num1, num2):
return num1 + num2

# Example usage:
calc = Calculator()
result = calc.add(10, 20)
print(result) # Output: 30

Can we add 2 lists together in Python?

Yes, you can concatenate (combine) two lists together using the + operator in Python.

# Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]

combined_list = list1 + list2
print(combined_list) # Output: [1, 2, 3, 4, 5, 6]

How to add numbers from different data types in Python?

Python supports automatic type conversion during arithmetic operations. When adding numbers of different types (like integers, floats, or even other types), Python will convert them to a compatible type if necessary.

# Example:
int_num = 10
float_num = 2.5
complex_num = 1 + 3j

result = int_num + float_num
print(result) # Output: 12.5 (integer + float)

result = float_num + complex_num
print(result) # Output: (3.5+3j) (float + complex)


Previous Article
Next Article

Similar Reads

Python Easy-Login Module
Easy-Login module is that library of Python which helps you to login in your social accounts like Facebook, Instagram, Twitter, Linkedin, Reddit etc through Python without opening the sites manually . Installation This module does not come built-in with Python. You need to install it externally. To install this module type the below command in the
2 min read
30 Easy Python Projects for Kids: Cool, Fun, and Educational
Looking for fun and simple ways to teach your kids Python programming? This Python Project for Kids is ideal for you! Python projects should be both creative, educational, and enjoyable. We’ve gathered simple, beginner-friendly Python projects that kids will enjoy. They can make games, build apps, and learn Python step-by-step. Whether your child i
15+ min read
Blockchain as a Service Platform - Easy to use
With the growth of the crypto market, the demand for blockchain has increased and people are seeking various possibilities of growth and taking interest in blockchain as a service platform. There are so many applications of blockchain which are the best things of blockchain as a tool platform for business. Its applications are making the scope of B
6 min read
Python program to add two binary numbers
Given two binary numbers, write a Python program to compute their sum. Examples: Input: a = "11", b = "1" Output: "100" Input: a = "1101", b = "100" Output: 10001Approach: Naive Approach: The idea is to start from the last characters of two strings and compute digit sum one by one. If the sum becomes more than 1, then store carry for the next digit
4 min read
Python program to add two Octal numbers
Given two octal numbers, the task is to write a Python program to compute their sum. Examples: Input: a = "123", b = "456" Output: 601 Input: a = "654", b = "321" Output: 1175Approach: To add two octal values in python we will first convert them into decimal values then add them and then finally again convert them to an octal value. To convert the
2 min read
Python Program To Add Two Numbers Represented By Linked Lists- Set 1
Given two numbers represented by two lists, write a function that returns the sum list. The sum list is a list representation of the addition of two input numbers. Example: Input: List1: 5->6->3 // represents number 563 List2: 8->4->2 // represents number 842 Output: Resultant list: 1->4->0->5 // represents number 1405 Explanation: 563 + 842 = 1405
4 min read
Python Program to add two hexadecimal numbers
Given two hexadecimal numbers, write a Python program to compute their sum. Examples: Input: a = "01B", b = "378" Output: 393 Explanation: B (11 in decimal) + 8 = 19 (13 in hex), hence addition bit = 3, carry = 1 1 + 7 + 1 (carry) = 9, hence addition bit = 9, carry = 0 0 + 3 + 0 (carry) = 3, hence addition bit = 3, carry = 0 01B + 378 = 393 Input:
6 min read
Communication Between two Programs using JSON
JSON stands for JavaScript Object Notation. To communicate between computer and human we use a programming language. To communicate between two programs, there must be a common data format and here we use JSON format. Let us say you have an application with Frontend written in Python and Backend written in Java. Now you need to communicate between
3 min read
Using lambda in GUI programs in Python
Python Lambda Functions are anonymous function means that the function is without a name. In this article, we will learn to use lambda functions in Tkinter GUI. We use lambda functions to write our code more efficiently and to use one function many times by passing different arguments. We use the lambda function to pass arguments to other functions
3 min read
Output of Python Programs | (Dictionary)
Prerequisite: Dictionary Note: Output of all these programs is tested on Python3 1.What is the output of the following of code? a = {i: i * i for i in range(6)} print (a) Options: a) Dictionary comprehension doesn’t exist b) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6:36} c) {0: 0, 1: 1, 4: 4, 9: 9, 16: 16, 25: 25} d) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5
2 min read
Structuring Python Programs
In this article, you would come to know about proper structuring and formatting your python programs. Python Statements In general, the interpreter reads and executes the statements line by line i.e sequentially. Though, there are some statements that can alter this behavior like conditional statements. Mostly, python statements are written in such
7 min read
Alphabet Pattern Programs in Python
Patterns are a valuable exercise for enhancing logical thinking and coding skills. Using loops in Python, we can create diverse alphabetical patterns like stars, squares, pyramids, and triangles. In this discussion, we'll explore Python programs for printing these patterns using simple iteration and for loops. Before printing Python patterns, know
11 min read
Writing Memory Efficient Programs Using Generators in Python
When writing code in Python, wise use of memory is important, especially when dealing with large amounts of data. One way to do this is to use Python generators. Generators are like special functions that help save memory by processing data one at a time, rather than all at once. The logic behind memory-efficient functions and Python generators is
5 min read
Programs for printing pyramid patterns in Python
Exploring and creating pyramid patterns in Python is an excellent way to enhance your programming skills and gain a deeper understanding of loops and control structures. By modifying and experimenting with the provided examples, you can create a variety of captivating patterns using Python. Exploring Pyramid Patterns in PythonPyramid patterns are s
9 min read
Output of Python programs | Set 7
Prerequisite - Strings in Python Predict the output of the following Python programs. These question set will make you conversant with String Concepts in Python programming language. Program 1[GFGTABS] Python var1 = 'Hello Geeks!' var2 = "GeeksforGeeks" print "var1[0]: ", var1[0] # statement 1 print "var2[1:5]:
3 min read
Output of Python programs | Set 8
Prerequisite - Lists in Python Predict the output of the following Python programs. Program 1 [GFGTABS] Python list = [1, 2, 3, None, (1, 2, 3, 4, 5), ['Geeks', 'for', 'Geeks']] print len(list) [/GFGTABS]Output: 6Explanation: The beauty of python list datatype is that within a list, a programmer can nest another list, a dict
3 min read
Output of Python programs | Set 9 (Dictionary)
Prerequisite: Dictionary 1) What is the output of the following program? [GFGTABS] Python dictionary = {'GFG' : 'geeksforgeeks.org', 'google' : 'google.com', 'facebook' : 'facebook.com' } del dictionary['google']; for key, values in dictionary.items(): print(key) dictionary.clear(); for key, v
3 min read
Output of Python programs | Set 10 (Exception Handling)
Pre-requisite: Exception Handling in PythonNote: All the programs run on python version 3 and above. 1) What is the output of the following program? [GFGTABS] Python data = 50 try: data = data/0 except ZeroDivisionError: print('Cannot divide by 0 ', end = '') else: print('Division successful ', end = '') try: data =
3 min read
Output of Python Programs | Set 18 (List and Tuples)
1) What is the output of the following program? [GFGTABS] PYTHON L = list('123456') L[0] = L[5] = 0 L[3] = L[-2] print(L) [/GFGTABS]a) [0, '2', '3', '4', '5', 0] b) ['6', '2', '3', '5', '5', '6'] c) ['0', '2', '3', '5', '5', '0'] d) [0, '2', '3', '5', '5', 0] Ans. (d) Explanation: L[0] is '1' and L[5] is '6', both of these elements will be
3 min read
Output of Python Programs | Set 19 (Strings)
1) What is the output of the following program? [GFGTABS] PYTHON3 str1 = '{2}, {1} and {0}'.format('a', 'b', 'c') str2 = '{0}{1}{0}'.format('abra', 'cad') print(str1, str2) [/GFGTABS]a) c, b and a abracad0 b) a, b and c abracadabra c) a, b and c abracadcad d) c, b and a abracadabra Ans. (d) Ex
3 min read
Output of Python Programs | Set 22 (Loops)
Prerequisite: LoopsNote: Output of all these programs is tested on Python3 1. What is the output of the following?[GFGTABS] Python mylist = ['geeks', 'forgeeks'] for i in mylist: i.upper() print(mylist) [/GFGTABS][‘GEEKS’, ‘FORGEEKS’].[‘geeks’, ‘forgeeks’].[None, None].Unexpected Output: 2. [‘geeks’, ‘forgeeks’]Explanation: The func
2 min read
Output of Python Programs | Set 24 (Dictionary)
Prerequisite : Python-Dictionary1. What will be the output? [GFGTABS] Python dictionary = {"geek":10, "for":45, "geeks": 90} print("geek" in dictionary) [/GFGTABS]Options: 10FalseTrueErrorOutput:3. TrueExplanation: in is used to check the key exist in dictionary or not. 2. What will be the output? [GFGTABS] P
2 min read
Python | Add comma between numbers
Sometimes, while working with currencies, we need to put commas between numbers to represent a currency, hence given a string, we can have a problem to insert commas into them. Let's discuss certain ways in which this task can be performed. Method #1 : Using str.format() The string format function can be used by supplying the valid formatter to per
5 min read
Extract numbers from a text file and add them using Python
Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Data file handling in Python is done in two types of files: Text file (.txt extension) Binary file (.bin extension) Here we are operating on the .txt file in Python. Through this program
4 min read
Python - Add space between Numbers and Alphabets in String
In this article, we delve into a practical Python solution to improve text readability by adding spaces between numbers and alphabets in strings by utilizing Python's powerful string manipulation capabilities. Input: test_str = 'ge3eks4geeks is1for10geeks' Output: ge 3 eks 4 geeks is 1 for 10 geeks Explanation: Numbers separated from Characters. Ad
9 min read
How to Add Numbers in a Csv File Using Python
When working with CSV files in Python, adding numbers in the CSV file is a common requirement. This article will guide you through the process of adding numbers within a CSV file. Whether you're new to data analysis or an experienced practitioner, understanding this skill is vital for efficient data management CSV (Comma-Separated Values): A common
3 min read
Python program to add two matrices
Prerequisite : Arrays in Python, Loops, List Comprehension Program to compute the sum of two matrices and then print it in Python. We can perform matrix addition in various ways in Python. Here are a two of them. Examples: Input : X= [[1,2,3], [4 ,5,6], [7 ,8,9]] Y = [[9,8,7], [6,5,4], [3,2,1]] Output : result= [[10,10,10], [10,10,10], [10,10,10]]U
2 min read
Python Program to Add Two Matrices
Given two matrices X and Y, the task is to compute the sum of two matrices and then print it in Python. Examples: Input : X= [[1,2,3], [4 ,5,6], [7 ,8,9]] Y = [[9,8,7], [6,5,4], [3,2,1]] Output : result= [[10,10,10], [10,10,10], [10,10,10]]Table of Content Add Two Matrices Using for loopAdd Two Matrices Using List ComprehensionAdd Two Matrices Usin
4 min read
Pandas Exercises and Programs
Pandas is an open-source Python Library that is made mainly for working with relational or labelled data both easily and intuitively. This Python library is built on top of the NumPy library, providing various operations and data structures for manipulating numerical data and time series. Pandas is fast and it has high performance & productivit
6 min read
How to open External Programs using Tkinter?
Prerequisite: Tkinter, os Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. In this article, w
2 min read
Article Tags :
Practice Tags :