Progress

Python Program to add two numbers: Beginners Guide

Python Program to add two numbers: Beginners Guide

There are many ways to add two numbers in Python. The sum function is also very helpful in finding the sum of numbers in Python.

Some more Python programs:

Python program code to manually add two numbers

Copy
x = 5
y = 7
#Manually add two numbers
added = x+y

print("The sum of {0} and {1} is {2}".format(x,y,added))
Output
The sum of 5 and 7 is 12

This is the most common and the simplest way to find the sum of two numbers in python. We manually add them using the addition operator and print the results.

The format() method is used with strings, you can assume it as a way to fill placeholders which are defined as {index}. The index will be the index position of argument inside format method.

Python program Code to add two numbers using user input

The more realistic situation will be to take input from the user and add the numbers.

Copy
#Take input from user and convert it to integer
x = int(input("Enter x: "))
y = int(input("Enter y: "))

#Advance way to do same as above
#x,y = map(int,input("Enter Two Numbers separated by space.\n").split(" "))

added = x+y

print("The sum of {0} and {1} is {2}".format(x,y,added))
Output
The sum of 5 and 6 is 11

We take input using the standard input() function at line 2 and 3. The input() function returns string so we need to convert it to an integer, int() function is used to convert the return value of the input to an integer.

Then we can manually add both the numbers and print them.

Sum of two numbers in Python using one line of code

Copy
print(int(input("Enter x: "))+int(input("Enter y: ")))
Output
Enter x: 5
Enter y: 6
11

At first, the input() function of x will run and then input() function of y will run then the sum of both will be printed.

Bonus Tip (Advanced):

Instead of manually taking inputs, we can use unpacking to take both inputs separated by space.

Copy
x,y = map(int,input("Enter Two Numbers separated by space.\n").split(" "))

This is the real beauty of python.

If we break it down then it will become easy to understand. The input() function takes the input separated by space and returns a string.

Split method is attached to input() which takes the input string and splits it based on space and return a list containing items.

Copy
"1 2 3 4 5".split(" ")
Output
['1', '2', '3', '4', '5']

At last, the map function takes each element of the list and passes it through int() function to make it an integer (return object of type map).

Copy
list(map(int, ['1', '2', '3', '4', '5']))
Output
[1, 2, 3, 4, 5]

The last step is unpacking.

Copy
a,b,c = [1, 2, 3]
print(a, b, c)
Output
1 2 3
Share the Post ;)

Related Posts