Python programs · Basics
Python program to add two numbers
Adding two numbers is the smallest complete program: read input, calculate, show the result. It also shows why input() must be converted to a number first.
Approach
- Read the first number and convert it with
int(). - Read the second number and convert it too.
- Add them and print the sum.
The program
a = int(input()) b = int(input()) print("Sum:", a + b)
Sample run
Input
12 30
Output
Sum: 42
How the code works
input() returns text, so int() turns each line into a whole number. If you skipped the conversion, + would join the two pieces of text instead of adding them: "12" + "30" gives 1230. Use float() instead of int() for numbers with decimals.
Try changing it
- Change
inttofloatto add decimals such as 2.5 and 3.75. - Read both numbers on one line with
a, b = map(int, input().split()).
Common mistakes
- Forgetting
int(), which joins the texts instead of adding the numbers. - Typing both numbers on one line when the program reads one number per line.