Home / Python / Example programs / Basics

Python program: Add two numbers

Add two numbers and print the result in a sentence.

The code

a = 12.5
b = 7

total = a + b
print(f"{a} + {b} = {total}")

# with input, the numbers arrive as text and must be converted:
# a = float(input("First number: "))
# b = float(input("Second number: "))

Output

12.5 + 7 = 19.5

How it works

Variables hold the numbers, + adds them, and an f-string puts the values into the sentence. If the numbers come from input(), convert them with float() first, or Python joins them as text ("12.5" + "7" is "12.57").

Python features used

Learn the ideas behind it in the free lesson Values, Variables & Numbers.