In this sample program, you will learn to find the sum of two numbers in Python and show it using the print() function.
Finding the sum of two numbers is one of the most basic operations in computer programming. It is used in a wide variety of applications, such as arithmetic calculations, financial analysis, and scientific computing.
Introduction
In this extended tutorial, we’ll not only learn how to write a Python program to find the sum of two numbers but also explore various concepts and techniques that can enhance your Python programming skills.
Before we begin, ensure you should have the basic Python programming knowledge:
To understand the demo programs, you must have a basic understanding of the Python fundamentals. And, you can grasp it in no time by following the above tutorials.
Firstly, let’s start with the most simple approach.
Sample Code: Sum of Two Numbers Entered by The User
In Python, there are several ways to find the sum of two numbers. The most straightforward way is to use the + operator. The + operator adds two numbers and returns the result.
For example, the following code adds the numbers int1 and int2 and prints the result to the console:
# Find sum of two integer numbers int1 = input('Enter first integer: ') int2 = input('Enter second integer: ') # Add two integer numbers sum = int(int1) + int(int2) # Show the sum print('The sum of {0} and {1} is {2}'.format(int1, int2, sum))
The output of the above code is as follows:
Enter first integer: 11 Enter second integer: 22 The sum of 11 and 22 is 33
You can change the (+) operator with the subtraction (-), multiplication (*), division (/), or the floor division (//) operator to perform different operations on the two numbers.
Other ways to find the sum of two numbers
In addition to the + operator, there are a few other ways in Python. Let’s find out.
Using the built-in sum() function
The sum() function takes an iterable of numbers as input and returns the sum of all the elements in the iterable. For example, the following code finds the sum of the numbers in the list [10, 20, 30] and prints the result to the console:
listofnumbers = [11, 22, 33] sum = sum(listofnumbers) print(sum) # 67
Using a lambda function
A lambda function is a single-line anonymous function in Python. We can have it to perform simple operations, such as finding the sum of two numbers.
For example, the following code defines a lambda function that takes two numbers as input and returns their sum:
sum_of_two_numbers = lambda num1, num2: num1 + num2
This lambda function can then be called in the following manner:
sum = sum_of_two_numbers(10, 20) print(sum) # 30
Try executing the above Python programs yourself. However, in order to dive deeper, you must practice with our 40 Python exercises for beginners.