Write Python Program to Add Two Numbers | Different Methods | Python Programming

Published: 22 December 2022
on channel: Developer Advocates Aspirant
1,285
7

To add two numbers in Python, you can use the following code:
def add(a, b):
return a + b
print(add(3, 4))

This code defines a function add that takes two arguments a and b, and returns their sum. The function is then tested by calling it with the arguments 3 and 4, and the result is printed to the console using the print() function.
You can also add two numbers using the + operator directly:

a = 3
b = 4
c = a + b
print(c) Output: 7
This code sets the variables a and b to the values 3 and 4, respectively, and then adds them using the + operator. The result is stored in the variable c and printed to the console.

You can also use the input() function to get the numbers from the user and then add them:

Get the numbers from the user then Convert the input to integers then Add the numbers and print the result.

This code gets the numbers from the user by calling the input() function and prompts the user to enter the values. The input is then converted to integers using the int() function and added using the + operator. The result is stored in the variable c and printed to the console using the print() function and string formatting.

You can also use the sum() function from the builtins module to add multiple numbers:


import builtins

Add three numbers
result = builtins.sum([3, 4, 5])
print(result) Output: 12


This code imports the sum() function from the builtins module and uses it to add the numbers 3, 4, and 5. The result is stored in the variable result and printed to the console.


On this page of the site you can watch the video online Write Python Program to Add Two Numbers | Different Methods | Python Programming with a duration of hours minute second in good quality, which was uploaded by the user Developer Advocates Aspirant 22 December 2022, share the link with friends and acquaintances, this video has already been watched 1,285 times on youtube and it was liked by 7 viewers. Enjoy your viewing!