Python Program to Multiply Two Numbers Using Command Line Arguments

In this article, we will learn about python program to multiply two numbers using command line arguments.

Getting Started

The task is to take two numbers as input using command line arguments and return it’s product. For example,

If a = 7 and b = 4, output is 28.

Using sys.argv in sys module in python, we can take input from command line.

Using User Input (Command Line Arguments)

Pseudo Algorithm

  • At first, import sys module.
  • Then, read input from command line using sys.argv.
  • Then, store the result in variables.
  • Finally, multiply those two numbers using multiplication operator (i.e. * operator).
  • Method 1

     
    import sys
    m, n = sys.argv[1:3]
    print("Result:", int(m) * float(n))
    

    Output:

     
    Result: 20.0
    

    Run above code using command line arguments as 10 and 2.

  • Method 2

    If we don’t want to apply restriction on how many numbers can be read from command line, we can skip second parameter as shown below –

     
    import sys
    m, n = sys.argv[1:]
    print("Result:", float(m) * float(n))
    

    Output:

     
    Result: 20.0
    

    Run above code using command line arguments as 10 and 2.

That’s how we can write python program to multiply two numbers using command line arguments.

Reference: Multiplication

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

Leave a Reply