In this article, we will learn about python program to multiply two integers with examples.
Getting Started
The task is to add one integer with another integer number in python. For example,
If a = 2 and b = 5, then output is 2 + 5 = 7.
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 multiply two integers in python using multiplication operator (i.e. * operator) as shown below –
n1 = 15 n2 = 6 result = n1 * n2 # Get product of two integers using * operator print("Result:", result)
Output:
Result: 90
Using User Input
If we want to take two integers as input from user and then multiply it, we can do so as shown below –
- We can read input from console using input() function.
- Then, type cast read value into integer using int.
- Multiply using multiplication operator (i.e. * operator).
n1 = int(input("Enter a number")) n2 = int(input("Enter another number")) result = n1 * n2 print("Product of {0} and {1} is {2}" .format(n1, n2, result))
Output:
Enter a number 23 Enter another number 6 Product of 23 and 6 is 138
Using User Input (Command Line Arguments)
Till now, we have seen how to accept value from user using terminal. Now, we will see how to read value using command line arguments.
-
Method 1
- sys.argv is used to read input as command line arguments. It is present in sys module in python.
- Then, we type cast read value into integer using int.
- After that, multiply both values and print it using print() function.
import sys n1, n2 = sys.argv[1:3] print("Result:", int(n1) * int(n2))
Output:
Result: 138
Run above code with command line arguments as 23 and 6.
n1, n2 = sys.argv[1:3] reads two values from console and store it in variable n1 and n2.
-
Method 2
If we don’t want to restrict number of items to be read from command line arguments, we can omit second parameter from sys.argv[1:3] as shown below –
import sys n1, n2 = sys.argv[1:] print("Result:", int(n1) * int(n2))
Output:
Result: 138
Run above code with command line arguments as 23 and 6.
Using Lambda
Using lambda and multiplication operator (* operator), we can multiply two integers as shown below –
if __name__ == "__main__" : n1 = 17 n2 = 24 # Multiply two integers multiply_twoNum = lambda n1, n2 : n1 * n2 print("Result:", multiply_twoNum(n1, n2))
Output:
Result: 408
Using Function
Below code contains a function multiplyIntegers that wraps logic to multiply two integers in python –
def multiplyIntegers(n1, n2): return n1 * n2 print("Result:", multiplyIntegers(15, 28))
Output:
Result: 420
That’s how we can write python program to multiply two integers with examples.
Reference: Multiplication
Learn about more python examples at – https://tutorialwing.com/python-tutorial/