Python Program to Divide Two Numbers Using Command Line Arguments

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

Getting Started

The task is to take input from user using command line arguments and divide them. Then, print the result.

We can take input from command line argument using sys.argv present in sys module in python.

Once input is taken from user, we can divide them using division operator (i.e. / operator).

  • Method 1

     
    import sys
    y1, y2 = sys.argv[1:3]
    result = int(y1) / float(y2)
    print("Result:", result)
    

    Output:

     
    Result: 8.789
    

    Run above code using command line arguments as 45 and 5.12.

  • Method 2

    If you don’t want to restrict input from user two only two numbers, omit the second parameter from sys.argv as shown below –

     
    import sys
    y1, y2 = sys.argv[1:]
    result = float(y1) / float(y2)
    print("Result:", result)
    

    Output:

     
    Result: 8.789
    

    Run above code using command line arguments as 45 and 5.12.

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

Reference: Division

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

Leave a Reply