Signup/Sign In
PUBLISHED ON: JULY 7, 2021

Python Program to add two numbers

In this tutorial, we will learn how to write a basic program of adding two numbers in Python. Our program should take two inputs from the user and return their sum. To take input from the user in Python, we use a function called input(). It is an inbuilt function that takes input from the user and always converts it to string.

To take integer input we use the int() function which is also a predefined function. The code of our program should take two user inputs as follows and return the sum of those numbers as output. For example

Input- 2,5

Output- 7

Now, let us move forward to understand the working of the code.

Algorithm

Step 1- Define a function Sum_of_two_num() to add two numbers

Step 2- Pass two numbers as parameters and add them

Step 3- Declare a variable sum to store the sum of numbers

Step 4- Take user input of two numbers

Step 5- Call function Sum_of_two_num() and pass inputs as parameter

Step 6- Declare a variable to store the value returned by the function

Step 7- Print sum

Python Program

Look at the program to understand the implementation of the above-mentioned approach.

def Sum_of_two_num(n,m):
    sum=n+m
    return sum

#take user input    
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))

x=Sum_of_two_num(a,b)

print("Sum of",a,"and",b,"is",x)


Enter first number:2
Enter second number:4
Sum of 2 and 4 is 6

Conclusion

In this tutorial, we learned how to add two numbers using the Python programming language. We defined a function that accepts two user inputs as parameters. In the function definition, we declared a variable sum to store the sum of the two numbers. The value of the variable sum was returned by the function. We declared another variable that catches the value returned by the function and used this variable to display the output.



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.