Add Two Numbers in Python: 5 Methods with Code
Five Python methods to add two numbers: + operator, function, f-string one-liner, float input, and bitwise XOR. Code, output, and when to use each.
Adding two numbers in Python has five standard methods, each testing a different layer of language knowledge. The methods are the + operator, a function-based version, an f-string one-liner, float() input for decimals, and a bitwise XOR loop that adds without using + at all.
All five appear in Python coding-round questions across Indian campus placements, and three of them appear in the first ten exercises of every introductory Python course. The difference is not which answer they produce. The difference is which Python construct they exercise.
Prerequisites and Setup
This program uses three Python building blocks:
- Variables and data types:
intstores whole numbers;floatstores decimals. The+operator is overloaded for both. - The
input()function: theinput()built-in reads a line from standard input and always returns a string. Wrap it withint()orfloat()to convert to a number. - Output with
print(): prints to standard output. Modern Python uses f-strings (PEP 498) for formatted output.
Python 3.x is assumed throughout. No imports are needed for any of the five methods.
Input Format and Sample Run
The standard version of this problem reads two numbers from the user and prints their sum.
Sample Input and Output
- Input line 1:
10 - Input line 2:
20 - Expected output:
The sum is: 30
The string-concatenation trap
input() returns a string. If you forget the int() cast and write input() + input(), Python concatenates the two strings instead of adding them.
- Typed input:
10, then20 - Without cast:
"10" + "20"produces"1020", not30. - With cast:
int("10") + int("20")produces30.
This single-line confusion is the most common bug in the first Python exercise. Every method below wraps input() in a numeric cast for that reason.
Method 1: Using the + Operator
The simplest, most idiomatic version. The + operator on two int values returns their sum.
Algorithm
- Step 1: Read the first number with
int(input(...)). - Step 2: Read the second number the same way.
- Step 3: Print the sum.
Python Code
# Add two numbers using the + operator
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
print("The sum is:", a + b)
Sample Run
- Input:
10, then20 - Output:
The sum is: 30
This is the answer to use unless the question explicitly forbids the + operator. It is also the version every linter and code reviewer expects.
Method 2: Using a Function
Wrapping the addition in a function separates “what the program does” from “how the inputs are read.” Placement coding rounds prefer this version because it shows modular thinking.
Algorithm
- Step 1: Define a function
add(a, b)that returnsa + b. - Step 2: Read both numbers from the user.
- Step 3: Call
add()and print the result.
Python Code
# Add two numbers using a function
def add(a, b):
return a + b
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
print("The sum is:", add(a, b))
Sample Run
- Input:
10, then15 - Output:
The sum is: 25
The function version is also the easiest to extend. Adding a third number, swapping int for float, or adding a guard for invalid input all change one place instead of three. The same modular pattern shows up in the Python calculator program, where four arithmetic operations are wrapped into one calculate() function.
Method 3: Floating-Point Input with float()
When the input has a decimal point, int() fails with a ValueError. Switching the cast to float() accepts decimals and returns a float result.
Python Code
# Add two floating-point numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
print(f"The sum of {num1} and {num2} is {num1 + num2}")
The output line uses an f-string, which is the modern Python way to embed variables inside a string.
Sample Run
- Input:
15.5, then26.4 - Output:
The sum of 15.5 and 26.4 is 41.9
A subtle floating-point caveat: 0.1 + 0.2 in Python evaluates to 0.30000000000000004, not exactly 0.3. This is not a Python bug. It is how IEEE 754 binary floating-point represents decimals across every language. For most additions the imprecision is invisible. For currency or exact decimal arithmetic, use the decimal module instead.
Method 4: Single-Line Version
For the absolute shortest form, nest the inputs and the print into one line.
Python Code
# Add two numbers in a single line
print("The sum is:", float(input("Enter the first number: ")) + float(input("Enter the second number: ")))
Sample Run
- Input:
67, then21 - Output:
The sum is: 88.0
This compresses three lines into one. It is shorter to type but harder to read, and harder still to debug. The only place this version belongs is a coding-round question that explicitly asks for a one-liner solution.
The output is 88.0 (a float) because each input was cast with float(). Switch both casts to int() and the output becomes 88 (an int).
Method 5: Adding Without the + Operator (Bitwise)
A frequent twist on this question in DSA rounds: “Add two numbers without using the + operator.” The standard answer uses bitwise XOR for the partial sum and bitwise AND with a left shift for the carry.
How it works
Binary addition without a + reduces to two operations:
- The XOR (
^) of two bits gives the sum bit when there is no carry. - The AND (
&) of two bits gives the bit positions where a carry is generated. - Shifting the carry left by one (
<<1) moves it into the next column, just like long-hand addition.
Repeat until the carry is zero, and the XOR running result is the sum.
Python Code
# Add two numbers using only bitwise operators
def add_without_plus(a, b):
while b != 0:
carry = a & b
a = a ^ b
b = carry << 1
return a
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
print("The sum is:", add_without_plus(a, b))
Sample Run
- Input:
12, then24 - Output:
The sum is: 36
Step-by-step trace for 12 + 24
The binary representations: 12 = 1100, 24 = 11000.
- Iteration 1:
carry = 12 & 24 = 01000 = 8.a = 12 ^ 24 = 10100 = 20.b = 8left-shift1=16. - Iteration 2:
carry = 20 & 16 = 10000 = 16.a = 20 ^ 16 = 00100 = 4.b = 16left-shift1=32. - Iteration 3:
carry = 4 & 32 = 0.a = 4 ^ 32 = 36.b = 0. Loop exits. - Return
a = 36.
The XOR pass adds the bits where they differ; the AND-and-shift pass propagates the carry into the next column. The loop ends when there is no carry left, and the final XOR result is the answer.
This is a hardware-flavoured exercise that turns up at companies that test low-level reasoning. Knowing the trick is worth roughly two minutes of practice.
Comparing the Five Methods
| Method | Lines of code | Handles floats | Uses + operator | Best for |
|---|---|---|---|---|
+ operator | 3 | With float() cast | Yes | The default answer |
| Function | 5 | With float() cast | Yes | Modular code, placement rounds |
float() input + f-string | 3 | Yes | Yes | Decimal inputs |
| Single line | 1 | Yes | Yes | One-liner constraint only |
| Bitwise XOR + carry | 7 | No (integers only) | No | ”Without + operator” prompt |
The + operator is the right answer in 95 of 100 cases. The function version is what to write when the question asks for “modular code.” The bitwise version is the answer reserved for the one prompt that bans +.
Edge Cases and Variants
Negative numbers
Python’s + operator handles negative integers and negative floats with no special case. (-5) + 3 returns -2. The function-based version inherits this for free.
The bitwise version also works for negatives in Python because Python integers are arbitrary precision and use a logical two’s-complement representation. The same XOR and AND trick adds (-12) + 24 = 12 correctly.
Very large integers
Python integers have no fixed width. Adding two 50-digit numbers works with the same +:
a = 12345678901234567890123456789012345678901234567890
b = 98765432109876543210987654321098765432109876543210
print(a + b)
# 111111111011111111101111111110111111111011111111100
No BigInteger library is needed. This is one of the things Python gets right by default, and one reason it is the standard teaching language at most Indian engineering colleges.
Multiple input formats
Some placement-test platforms feed both numbers on a single line, separated by a space. The fix is one line:
a, b = map(int, input("Enter two numbers separated by a space: ").split())
print("The sum is:", a + b)
split() breaks the string into a list of pieces; map(int, ...) casts each piece; the tuple unpacking assigns the two values to a and b. This pattern shows up across the Python basic programs catalogue and is worth committing to memory.
Adding More Than Two Numbers
Adding three numbers extends the same idea: replace one cast and one variable. Adding n numbers from a list is what the sum() built-in is for:
numbers = [10, 20, 30, 40, 50]
print(sum(numbers)) # 150
When the comparison flips from “add” to “pick the larger,” the structure stays identical and only the operator changes. That is what the greatest of two numbers in Python article walks through.
Where This Goes Next
A function that takes two inputs and returns one result is also the shape of every LLM tool call. Method 2’s def add(a, b): return a + b and the modern equivalent def call_llm(prompt): return response are the same pattern: read input, transform, return. TinkerLLM (₹299) is the playground where that second function becomes real, with the same int(input(...)) muscle memory replaced by a prompt and a model call.
Primary sources
Frequently asked questions
Why does input() + input() give the wrong answer in Python?
Because input() always returns a string. Two strings joined with + are concatenated, not added. The fix is to wrap each input() in int() or float() so Python performs arithmetic addition instead of string concatenation.
How do I add two numbers in Python without using the + operator?
Use the bitwise XOR-and-carry loop: a = a ^ b for the partial sum, carry = (a & b) << 1 for the carry, repeat until carry is zero. Method 5 in this article walks through it step by step.
Can Python add very large numbers without overflow?
Yes. Python integers have arbitrary precision — they grow as large as available memory allows. Adding two 100-digit numbers works with the same + operator, no special library needed.
Should I use int(input()) or float(input()) for adding two numbers?
Use int() if both inputs are whole numbers and the answer should be a whole number. Use float() if either input might have a decimal point, or if the test case shows a decimal output.
Why does 0.1 + 0.2 not equal 0.3 exactly in Python?
Floating-point numbers are stored in binary, and 0.1 and 0.2 cannot be represented exactly in base 2. The result is 0.30000000000000004. For exact decimal arithmetic, use the decimal module instead of float.
What is the f-string syntax for printing the sum of two numbers?
Use an f-string with curly braces around each variable: print(f'The sum of {a} and {b} is {a + b}'). The expression inside the braces is evaluated and inserted into the string at print time.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)