In this article, we will learn about python program to add two integers with examples
Getting Started
The task is to add one integer with another integer using python programming. For examples,
If a = 4 and b = 5. Then, output is (4 + 5) = 9.
We can do so in multiple ways –
- Simple Approach
- Using User Input
- Using User Input(Command Line Arguments)
- Using Lambda
- Using Function
Simple Approach
We can simply use + operator to add two integers in python as shown below –
x = 7 y = 8 result = x + y # Get sum of two integers using + operator print("result = ", result)
Output:
result = 15
Using User Input
Instead of taking static values in our program, we can also accept input from user. It can be done as below –
x = int(input("Enter a number")) y = int(input("Enter another number")) result = x + y print("sum of {0} and {1} is {2}" .format(x, y, result))
Output:
Enter a number 12 Enter another number 32 sum of 12 and 32 is 44
Using User Input (Command Line Arguments)
We can also take input as command line arguments using sys module in python. sys.argv reads input from command line.
For example,
-
Method 1
import sys a, b = sys.argv[1:3] print("sum is", int(a) + int(b))
Output:
sum is 3
In above code,
- sys.argv[1:3] reads input as command line arguments from position 1 till position 3 (excluding)
- a, b = sys.argv[1:3] means read input as command line arguemnts and stores in variable a and b
-
Method 2
If we don’t want to apply maximum count of values to be read as command line arguments, we can omit second argument in sys.argv as shown below –
import sys a, b = sys.argv[1:] print("sum is", int(a) + int(b))
Output:
sum is 3
-
Method 3
We can write previous code in more pythonic way as shown below –
import sys summ = sum(int(i) for i in sys.argv[1:]) print("sum is", summ)
Output:
sum is 3
Using Lambda
Using Lambda and + operator, we can add two integers in python as below –
if __name__ == "__main__" : num1 = 1 num2 = 2 # Adding two integers sum_twoNum = lambda num1, num2 : num1 + num2 print("sum =", sum_twoNum(num1, num2))
Output:
sum = 3
Using Function
We can wrap the logic to add two integers in a function as shown below –
def addTwoIntegers(a, b): return a + b print("sum =", addTwoIntegers(1, 2))
Output:
sum = 3
That’s how we can write python program to add two integers with examples
Reference: Addition
Learn about more python examples at – https://tutorialwing.com/python-tutorial/