Home » Python programs

Python program to find addition of two numbers (4 different ways)

Adding two numbers in Python: Here, we are going to learn various ways to find the addition of two numbers in python.
Submitted by Ankit Rai, on July 28, 2019

Take input of two numbers from the user and print their sum.

Example:

    Input:
    A = 2, B = 3

    Output:
    Sum = 5

Here, we are implementing the program to find the addition of two numbers using 4 different ways.

1) Simply take input from the user and typecast to an integer at the same time after that performing addition operation on the both number.

if __name__ == "__main__" :

    # take input from user
    a = int(input())
    b = int(input())

    # addition operation perform
    sum_num = a + b
    
    print("sum of two number is: ",sum_num)

Output

10
20
sum of two number is:  30

2) Using a user-defined function for doing the sum of two numbers.

# define a function for performing 
# addition of number
def sum_num(a,b) :
    
    return a + b

# Main code
if __name__ == "__main__" :

    a = int(input())
    b = int(input())

    print("sum of two number:",sum_num(a,b))

Output

10
20
sum of two number: 30

3) We are taking the input from user in one line after that typecast into an integer and stored them in the list then use sum() inbuilt function which returns the sum of elements of the list.

if __name__ == "__main__" :    
	# take input from the user in list
	a = list(map(int,input().split()))

	# sum function return sum of elements 
	# present in the list
	print("sum of two number is:",sum(a))

Output

10 20
sum of two number is: 30

4) We are taking the input from user in one line and store them in two different variables then typecast both into an integer at the time of addition operation.

if __name__ == "__main__" :
    
    # take input from the user in a and b variables
    a,b = input().split()

    # perform addition operation
    rslt = int(a) + int(b)
    
    print("sum of two number is:",rslt)

Output

10 20
sum of two number is: 30






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.