Skip to content
Devtoolry

Basics · beginner

Python Program to Add Two Numbers

Add two numbers in Python, first with fixed values and then with numbers read from input(), and learn why input() needs int() or float() before adding.

Adding two numbers is usually the first real program people write after "Hello, World". It looks trivial, but it teaches the most common beginner bug in Python: input() always returns text, and adding two pieces of text joins them instead of adding them.

The program below reads two numbers from standard input, converts them, adds them and prints the result with an f-string.

The program

Python
a = float(input())
b = float(input())
total = a + b
print(f"{a} + {b} = {total}")
print(f"Rounded: {round(total, 2)}")
Input (stdin)
2.5
4.25
Output
2.5 + 4.25 = 6.75
Rounded: 6.75

How it works

  1. input() reads one line from standard input as a string, for example "2.5".
  2. float() turns that string into a number. Use int() instead when you only expect whole numbers.
  3. a + b adds the two numbers and stores the result in total.
  4. The f-string puts the values into the sentence: anything inside {braces} is evaluated and printed.
  5. round(total, 2) keeps two decimal places, which hides tiny floating-point errors such as 0.1 + 0.2 = 0.30000000000000004.

Watch it run line by line

Step through the first two lines and watch a and b appear in the global frame as floats (2.5, not "2.5"). Then remove float() and visualize again: the values become strings and total becomes "2.54.25".

“Visualize step by step” opens the program in the Python Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.

Another way: Read both numbers from one line

When the input is "2 3" on a single line, split it first. map() applies int to each part, and the two results unpack into a and b.

Python
a, b = map(int, input().split())
print(a + b)
Input (stdin)
2 3
Output
5

Common mistakes

  • Forgetting int() or float(): input() returns a string, so "2" + "3" gives "23".
  • Using int() on a decimal such as "2.5" raises ValueError. Use float() when decimals are allowed.
  • Naming a variable sum shadows the built-in sum() function for the rest of the program. Use total instead.

Try it yourself

  • Read three numbers and print their average.
  • Print the difference, product and quotient of a and b as well.
  • Catch ValueError with try/except and print a friendly message when the input is not a number.

Open the program in the Python Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 Python examples, or write your own program in the online Python Compiler.