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.
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 5Output:
78.5398163397Test Case 2: Radius 8
python CircleArea.py 8Output:
201.0619298297Test Case 3: Radius 10
python CircleArea.py 10Output:
314.1592653590Conclusion
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.