Python program to add two numbers

Learn to add numbers in Python 3.

Python program to add two numbers

Method 1 - Simple addition

Code

num1 = 10
num2 = 5
  
# Adding both numbers 
sum = num1 + num2 
  
# printing values 
print(f"Sum of {num1} and {num2} is {sum}") 

Output

Sum of 10 and 5 is 15

Method 2 - Adding two number provided by user input

Code

num1 = input("Enter first number: ")
num2 = input("Enter second number: ")

# User might enter float
sum = float(num1) + float(num2)

# We get a float value
print(f"The sum of {num1} and {num2} is {sum}")

Output

Enter first number: 10
Enter second number: 2
The sum of 10 and 2 is 12.0

Now be careful with this method. We are using the input() built in function of Python. Since it returns a string, we convert the string into number using the float() function. Then, the numbers are added.

Using the built in int() function will chop off the decimal places.

  1. Python Strings
  2. f-strings

Subscribe to Pylenin

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe