W3docs

Add Two Numbers

Learn how to add two numbers in Python using the + operator, sum(), and functools.reduce(). Covers integers, floats, and user-input conversion.

Adding two numbers is one of the first arithmetic operations you need to understand in Python. Python supports several approaches: the plain + operator for the simplest cases, the built-in sum() function when working with a collection, and functools.reduce() for functional-style code. This page covers all three, plus the important step of converting user input to a numeric type before adding.

Method 1: Using the + Operator

The addition operator + is the most direct way to add two numbers. It works with integers, floats, and complex numbers.

python— editable, runs on the server

The same operator works with floats without any changes:

x = 3.5
y = 1.2
print(x + y)   # Output: 4.7

Variable naming tip: avoid naming a variable sum — it shadows Python's built-in sum() function and can cause confusing bugs later in your code.

Method 2: Adding Numbers from User Input

When a user types a number, Python receives it as a string. You must convert it to an integer with int() or to a floating-point number with float() before you can do arithmetic. See Python Casting for a full explanation of type conversion.

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
result = a + b
print("The sum is:", result)

If the input might contain decimals, use float() instead of int():

a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("The sum is:", a + b)

Method 3: Using the Built-in sum() Function

Python's built-in sum() function adds every item in an iterable (such as a list or tuple). It is the right tool when you have more than two numbers to add.

python— editable, runs on the server

sum() also accepts an optional start argument, which is added to the result:

total = sum([1, 2, 3], 10)   # 10 + 1 + 2 + 3
print(total)                  # Output: 16

This is useful when you want to accumulate into a running total.

Method 4: Using functools.reduce()

reduce() from the functools module applies a two-argument function repeatedly across a sequence, reducing it to a single value. For simple addition sum() is clearer, but reduce() is valuable when the combining function is more complex than +.

python— editable, runs on the server

You can also pass a lambda instead of a named function:

from functools import reduce

total = reduce(lambda x, y: x + y, [10, 20, 30, 40, 50])
print(total)   # Output: 150

Choosing the Right Approach

SituationRecommended approach
Adding two known values+ operator
Reading numbers from the keyboardint() / float() then +
Summing a list or tuplesum()
Applying a custom combining functionfunctools.reduce()
Was this page helpful?