Python Program to Add Two Numbers
Beginner · Basics
This program adds two numbers and prints their sum. It is one of the first programs students write, and it shows how Python keeps numbers in variables and does arithmetic with them.
Program
add_two_numbers.py
a = 15 # or: a = int(input("Enter the first number: "))
b = 27 # or: b = int(input("Enter the second number: "))
total = a + b
print("First number:", a)
print("Second number:", b)
print("Sum:", total)
Output
First number: 15 Second number: 27 Sum: 42
How it works
- The two numbers are stored in
aandb, and the comments show how to type them in withinput()instead. input()always returns text, soint()is needed to turn the text "15" into the number 15.a + badds the two numbers, and the result is stored intotal.- Each
print()shows a label followed by its value, with a space added between them.
Other ways to write it
Adding decimal numbers
Adding decimal numbers
a = 2.5 # or: a = float(input("Enter the first number: "))
b = 4.75 # or: b = float(input("Enter the second number: "))
total = a + b
print(f"{a} + {b} = {total}")
Output
2.5 + 4.75 = 7.25
float() accepts numbers with a decimal point, and the f-string prints the whole sum on one line.
Why int() matters
Why int() matters
a = "15" # this is what input() gives you: text
b = "27"
print("Joined as text:", a + b)
print("Added as numbers:", int(a) + int(b))
Output
Joined as text: 1527 Added as numbers: 42
With text, + joins the two strings and gives "1527". Converting with int() first gives the real sum, 42.
Try it yourself
Add a third number c and print the sum of all three.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises