Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Add Two Numbers in Python

Why does adding two Python inputs sometimes give 1020? This beginner addition program converts text with float before calculating and printing a numeric sum.

BeginnerBasic Python ProgramsExample 2 of 25
add-two-numbers.py
1# Program to add two numbers provided by the user
2
3# taking input from the user
4num1 = float(input("Enter first number: "))
5num2 = float(input("Enter second number: "))
6
7# adding the two numbers
8result = num1 + num2
9
10# displaying the result
11print("The sum is:", result)

Sample Output

The sum is: 30.0

10.0 + 20.0 produces a floating-point result of 30.0.

In this one

  • Convert input text with float
  • Distinguish addition from concatenation
  • Read comma-separated print arguments

How it works

  1. 1

    Read and convert the first response into num1.

  2. 2

    Convert the second response and add both numeric values into result.

  3. 3

    Print the label and result as separate arguments.

Edge cases

Decimal input

Enter 10.5 and 2.

float accepts both responses, and the sum is 12.5.

Blank response

Press Enter without a number.

float cannot convert an empty string, so this version raises ValueError.

What's going on

input() always returns a string. "10" + "20" is "1020", not 30. That one surprises everyone once. Here float converts each response before addition, so + works on numbers instead of joining text.

num1 and num2 hold 10.0 and 20.0 for the sample. result stores their sum. The comma in print separates arguments; print inserts a space between the label and the value. It is not string concatenation.

Use int when the lesson needs whole numbers, but int("10.5") raises ValueError. float("10") is fine. Blank or nonnumeric responses also raise ValueError here because this small program has no error handler. The shape is boring on purpose: read, convert, compute, print.

After this program

If the idea is still fuzzy, read Day 1: Introduction to Python in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 basic python programs, or see every topic on Python exercises.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why is the sample sum 30.0 rather than 1020?

Pick an answer to check it.

Question 2

Can int convert the text "10.5" directly?

Pick an answer to check it.

Questions people ask

Why is the sample sum 30.0 rather than 1020?

float converts both input strings, so + performs numeric addition.

Can int convert the text "10.5" directly?

No. int expects whole-number text and raises ValueError for "10.5".

Why is there a decimal point in 30.0?

Both operands are floats, so their sum is a float too.