Python program to add two numbers

Adding Two Numbers (Different Methods): Here, you will find different ways to add given two numbers using Python program. By Ankit RaiLast updated : August 20, 2023

Two numbers can be added in Python using these different methods/ways:

Input numbers and perform addition

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

Example

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

Using user-defined function

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

Example

# 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

Using input(), map(), and list() functions

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.

Example

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

Input values in one line, split them, and perform addition

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.

Example

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

Python Basic Programs »


Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.