Skip to content

Python Math: How to Calculate Area of a Circle from Command Line

Learn how to create a Python script that calculates the area of a circle from command-line input using math.pi and precise formatting to 10 decimal places.

Calculating the area of a circle is a fundamental programming exercise that bridges basic math with input handling. In this guide, you will create a Python script that accepts a radius via command-line arguments, calculates the area using the math module, and formats the output to a specific precision.

Understanding the Logic

To complete this task, we need to address three specific requirements:

  1. The Formula: The area of a circle is calculated as A = π r^2.
  2. The Input: Instead of hardcoding the radius or asking for input() during execution, we will pass the radius as a command-line argument (e.g., python script.py 10).
  3. The Output: The result must be formatted to exactly 10 decimal places.

Step 1: Importing Modules and Handling Input

We need two standard libraries:

  • sys: To access arguments passed to the script via the command line.
  • math: To access the value of Pi (π).

accessing sys.argv

The list sys.argv contains the command-line arguments.

  • sys.argv[0] is always the name of the script itself (CircleArea.py).
  • sys.argv[1] is the first argument passed by the user (the radius).
import sys

try:
    radius_arg = sys.argv[1]
    radius = float(radius_arg)
except IndexError:
    print("Error: Please provide a radius argument.")
    sys.exit(1)

Step 2: Implementing the Calculation

Now we combine the input with the math module and format the result.

Complete Script: CircleArea.py

Create a file named CircleArea.py and add the following code:

import sys
import math

radius = float(sys.argv[1])

area = math.pi * radius * radius

area_str = format(area, ".10f")

print(area_str)

Step 3: Running the Script

To test the script, you run it from your terminal, passing the radius value immediately after the filename.

Test Case 1: Radius 5

python CircleArea.py 5

Output:

78.5398163397

Test Case 2: Radius 8

python CircleArea.py 8

Output:

201.0619298297

Test Case 3: Radius 10

python CircleArea.py 10

Output:

314.1592653590

Conclusion

By using sys.argv, you can make your Python scripts dynamic and interactable from the shell.

  1. Import sys to read command-line inputs.
  2. Import math for accurate mathematical constants like pi.
  3. Use format(value, ".10f") to control the precision of your floating-point output.
Navigation