Editor

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

  1. The two numbers are stored in a and b, and the comments show how to type them in with input() instead.
  2. input() always returns text, so int() is needed to turn the text "15" into the number 15.
  3. a + b adds the two numbers, and the result is stored in total.
  4. 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.

All Python programs · CBSE class 12 practical file · Python exercises