PythonMastery

Add two numbers in Python

Read two numbers with input(), convert them with float() or int(), and print their sum. Also shows why '12' + '30' gives '1230'.

The program asks for two numbers, adds them with + and prints the sum. The one step that beginners often miss is converting the typed text into numbers first.

The program

python
first = float(input("Enter the first number: "))
second = float(input("Enter the second number: "))

total = first + second

print(f"{first} + {second} = {total}")

Typed in this example: 12.5, 7.25. Press Run to type your own.

output
Enter the first number: 12.5
Enter the second number: 7.25
12.5 + 7.25 = 19.75

How it works

Why you must convert

+ on two strings does not add them. It joins them end to end:

python
a = "12"
b = "30"

print(a + b)
print(int(a) + int(b))
output
1230
42

int or float

Use int() when the user must type whole numbers. Then 7 prints as 7 and not 7.0:

python
first = int(input("First whole number: "))
second = int(input("Second whole number: "))
print("Sum:", first + second)

Typed in this example: 25, 17. Press Run to type your own.

output
First whole number: 25
Second whole number: 17
Sum: 42

int("7.5") raises a ValueError, so use float() if decimals are allowed. The type conversion page shows what each conversion accepts.

Without input

If the numbers are already in your code, add them directly. sum() adds every number in a list:

python
a = 15
b = 27
print("Sum:", a + b)

print(sum([3, 4.5, 10]))
print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))
output
Sum: 42
17.5
0.30000000000000004
0.3

The last two lines show a normal property of floats: most decimal fractions cannot be stored exactly in binary, so a tiny error can appear. Use round() or an f-string such as f"{total:.2f}" when you print the result.

Learn the idea: Input & Output: Talking to Your User, Operators & Expressions