A Program to Sum Two Numbers

In this Python lesson, we will practice how to write a program to add two numbers and display it using the built-in print() function.

Example 1: Sum Two Numbers using + operator

# Program to add two numbers using + operator
num1 = 5.7
num2 = 2.5

# Sum the two numbers
result = num1 + num2

# Display the result
print('The sum of {0} and {1} = {2}'.format(num1, num2, result))

Output

The sum of 5.7 and 2.5 = 8.2

In the program above, we used the + operator to add two numbers stored in the variable of num1 and num2. The above numbers can be either integers or decimal/float numbers. Let’s look at another practice where we will calculate the sum of two numbers entered by the user.

Example 2: Sum Two Numbers Entered by a User

# Request inputs from user
num1 = float(input('Enter first number: '))
num2 = float(input('Enter second number: '))

# Sum the two numbers
result = num1 + num2

# Display the result
print('The sum of {0} and {1} = {2}'.format(num1, num2, result))

Output

Enter first number: 6.0
Enter second number: 4.3

The sum of 6.0 and 4.3 is 10.3

Using the input() built-in function in the above program, we requested the user to enter two numbers which were stored in the num1 and num2 variables respectively. We converted the user inputs to float because user inputs are saved as strings by default. We did not convert the to integer because we considered cases where user can input a decimal number instead of integer numbers. Hence, integer or float numbers entered by a user is summed and the result is displayed on the console.

Do you want to become an expert programmer? See books helping our students, interns, and beginners in software companies today (Click here)!

Leave a Comment

Python Tutorials