We will develop a python program to add two numbers without using + operator. We will give two numbers num1 and num2. Python programs will add these numbers using the XOR operator and & operator. We can take the help of a function to add two numbers in python. A function is a block of code that performs a specific task.
Add Two Numbers in Python with User Input Without using + Operator
We will take two numbers while declaring the variables. Then, call the function and the sum of numbers will be displayed on the screen.
# Python program to add two numbers without using + operator
def add_num(a,b): #user-defined function
while b != 0:
c = a & b #using and operator
a = a ^ b #using XOR operator
b = c << 1
return a
# take inputs
num1 = 2
num2 = 7
# calling function
sum = add_num(num1, num2)
# print sum of numbers
print('The sum of numbers {0} and {1} is {2}'
.format(num1, num2, sum))
Output:-
The sum of numbers 2 and 7 is 9
In the previous program, inputs are hardcoded in the program but in this program, inputs will be provided by the user.
# Python program to add two numbers without using + operator
def add_num(a,b): #user-defined function
while b != 0:
c = a & b #using and operator
a = a ^ b #using XOR operator
b = c << 1
return a
# take inputs
num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number: '))
# calling function
sum = add_num(num1, num2)
# print sum of numbers
print('The sum of numbers {0} and {1} is {2}'
.format(num1, num2, sum))
Output for the input values test-case-1:-
Enter first number: 12
Enter second number: 3
The sum of numbers 12 and 3 is 15
Output for the input values test-case-2:-
Enter first number: 98
Enter second number: 125
The sum of numbers 98 and 125 is 223
Python Program to Add Two Numbers Without using + Operator
This python program also performs the same task but in different ways. In this program, we add two numbers using -, *, and / operator.
# Python program to add two numbers without using + operator
def add_num(a,b): #user-defined function
if a!=b:
return (a*a-b*b)/(a-b)
else:
return 2*a
# take inputs
num1 = float(input('Enter first number: '))
num2 = float(input('Enter second number: '))
# calling function
sum = add_num(num1, num2)
# print sum of numbers
print('The sum of numbers {0} and {1} is {2}'
.format(num1, num2, sum))
Output for the input values test-case-1:-
Enter first number: 23
Enter second number: 9
The sum of numbers 23.0 and 9.0 is 32.0
Output for the input values test-case-2:-
Enter first number: 52.6
Enter second number: 25
The sum of numbers 52.6 and 25.0 is 77.6
Output for the input values test-case-3:-
Enter first number: 3.6
Enter second number: 0.91
The sum of numbers 3.6 and 0.91 is 4.51