Python Program to Multiply Two Numbers

In this article, we will learn about python program to multiply two numbers with examples

Getting Started

The task is to get product of two numbers in python using python programming language. For example,

If a = 10 and b = 2. Then, product is 10 * 2 = 20.

We can do so in multiple ways –

Simple Approach

We can simply multiply two number using multiplication operator (i.e. * operator) in python as shown below –

 
m = 10
n = 30

result = m * n  # Multiply using * operator
print("Multiply = ", result)

Output:

 
Multiply =  300

Using User Input

If we want to take user input, we can do so using input() built-in function in python. Then, we typecast input value into integer value using int.

Finally, we get product of two numbers in python using * operator.

 
m = int(input("Enter a number"))
n = int(input("Enter another number"))

result = m * n
print("Multiply of {0} and {1} is {2}" .format(m, n, result))

Output:

 
nter a number
20
Enter another number
5
Multiply of 20 and 5 is 100

Using User Input (Command Line Arguments)

We can also accept input as command line arguments using sys.argv present inside sys module in python.

Then, we get product of two numbers using * operator in python as shown below –

  • Method 1

     
    import sys
    a, b = sys.argv[1:3]
    print("Multiply is", float(a) * float(b))
    

    Output:

     
    Multiply is 30.0
    

    Run above program with command line arguments as 10 and 3.

    a, b = sys.argv[1:3] reads two values from command line and stores them in variable a and b.

  • Method 2

    If two don’t want to apply restriction on how many numbers are to be read from command line, we can omit second argument in sys.argv as shown below –

     
    import sys
    a, b = sys.argv[1:]
    print("Multiply is", int(a) * float(b))
    

    Output:

     
    Multiply is 30.0
    

    Run with argument as 10 and 3.

Using Lambda

Using lambda and multiplication operator, we can multiply two numbers in python as shown below –

 
if __name__ == "__main__" :
    n1 = 12
    n2 = 2

    # Multiply two numbers
    multiplyNum = lambda n1, n2 : n1 * n2
    print("Multiply =", multiplyNum(n1, n2))

Output:

 
Multiply = 24

Using Function

We can also write a function that returns product of two numbers in python as shown below –

 
def multiply(m, n):
    return m * n
 
print("Multiply =", multiply(12, 2))

Output:

 
Multiply = 24

That’s how we can write python program to multiply two numbers with examples.

Reference: Official Doc

Learn about more python examples at – https://tutorialwing.com/python-tutorial/

Leave a Reply