Python Program to add two numbers without addition operator

In this tutorial, you will learn writing a Python program to add two numbers without using addition operator.

Read This:  Write a program in Java to add two number without using third variable.

To perform addition without using addition(+) operator, we will use the concept of bitwise operators. Below is the program using python.

Add two number without + Operator in Python

def add_numbers(x, y):
    while y != 0:
        temp = x & y
        x = x ^ y
        y = temp << 1
    return x
 
num1 = 10
num2 = 15
sum_result = add_numbers(num1, num2)
print(f"Sum of {num1} and {num2} is: {sum_result}")

Output

Sum of 10 and 15 is: 25

Explanations

In the above program we have defined add_numbers function to perform addition operation. It takes two numbers x and y as input and return the sum as output.

Here we have used while loop to perform the iteration. Inside while loop there are some logics written to perform additions. Inside the while loop:

  1. temp = x & y calculates the carry by performing a bitwise AND operation on x and y.
  2. x = x ^ y calculates the sum of x and y without considering any carries. It uses the bitwise XOR operator to perform the addition.
  3. y = carry << 1 shifts the carry to the left by 1 position, effectively preparing it to be added in the next iteration.

The loop continues until y becomes zero, which means there is no more carry left. Finally, the function returns the sum, which is stored in x.

In the example above, the program adds num1 = 10 and num2 = 15, and the expected output is 25, which is the correct sum.