Add Two Numbers in Python

input() gives strings. Forget float() and you glue 10 and 20 into 1020.

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)

Output

Enter first number: 10
Enter second number: 20
The sum is: 30.0

In this one

  • input() is a string until you convert it
  • float("10") + float("20") is 30.0, not "1020"

What's going on

input() always returns a string. "10" + "20" is "1020", not 30. That one surprises everyone once.

float(...) turns the string into a number so + actually adds. Use int() if you only want whole numbers — then 10.5 will crash.

The shape is boring on purpose: read, convert, compute, print. You will copy this 50 times.

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.