Python Math: How to Calculate Area of a Circle from Command Line
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:
- The Formula: The area of a circle is calculated as
A = π r^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). - The Output: The result must be formatted to exactly 10 decimal places.
Python's math module provides a high-precision value for π via math.pi. Always use this constant instead of hardcoding 3.14.
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
# ✅ Correct: Access the second element of the list (index 1)
# Note: Command line arguments are strings, so we must cast to float.
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
# 1. Get command line argument (Radius)
# We assume the user provides a valid number as the first argument
radius = float(sys.argv[1])
# 2. Calculate the area of the circle
# Formula: Area = pi * r * r
area = math.pi * radius * radius
# 3. Format the result to 10 decimal places
# ".10f" means fixed-point notation with 10 digits after the dot
area_str = format(area, ".10f")
# 4. Print the result
print(area_str)
You can also calculate the square of the radius using the exponent operator: math.pi * (radius ** 2). Both methods are valid.
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.
- Import
systo read command-line inputs. - Import
mathfor accurate mathematical constants likepi. - Use
format(value, ".10f")to control the precision of your floating-point output.