Python Program to Calculate Area of Circle
You can calculate the area of a circle in Python by using
area = 3.14159 * radius ** 2, where radius is the circle's radius.Examples
Inputradius = 0
OutputArea of circle: 0.0
Inputradius = 5
OutputArea of circle: 78.53975
Inputradius = 10.5
OutputArea of circle: 346.3600725
How to Think About It
To find the area of a circle, you need the radius. The formula multiplies pi (about 3.14159) by the square of the radius. So, you get the radius, square it by multiplying it by itself, then multiply by pi to get the area.
Algorithm
1
Get the radius value from the user2
Calculate the area by multiplying pi with radius squared3
Print the calculated areaCode
python
radius = float(input("Enter the radius of the circle: ")) area = 3.14159 * radius ** 2 print("Area of circle:", area)
Output
Enter the radius of the circle: 5
Area of circle: 78.53975
Dry Run
Let's trace the program with radius = 5 through the code
1
Input radius
User enters 5, so radius = 5.0
2
Calculate area
area = 3.14159 * 5.0 ** 2 = 3.14159 * 25 = 78.53975
3
Print result
Output: Area of circle: 78.53975
| Step | Radius | Calculation | Area |
|---|---|---|---|
| 1 | 5.0 | N/A | N/A |
| 2 | 5.0 | 3.14159 * 5.0 ** 2 | 78.53975 |
| 3 | 5.0 | N/A | 78.53975 |
Why This Works
Step 1: Getting the radius
We use input() to get the radius from the user and convert it to a number with float() so we can do math.
Step 2: Calculating the area
We use the formula area = π × radius², where radius ** 2 means radius times radius.
Step 3: Showing the result
We print the area so the user can see the answer.
Alternative Approaches
Using math.pi constant
python
import math radius = float(input("Enter the radius: ")) area = math.pi * radius ** 2 print("Area of circle:", area)
This uses Python's built-in pi value for more accuracy.
Using a function
python
def circle_area(r): return 3.14159 * r ** 2 radius = float(input("Radius: ")) print("Area:", circle_area(radius))
Encapsulates calculation in a function for reuse.
Complexity: O(1) time, O(1) space
Time Complexity
The program does a fixed number of operations regardless of input size, so it runs in constant time.
Space Complexity
It uses a few variables and no extra data structures, so space used is constant.
Which Approach is Fastest?
All approaches run in constant time; using math.pi is slightly more accurate but not slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Hardcoded pi (3.14159) | O(1) | O(1) | Simple quick calculation |
| Using math.pi | O(1) | O(1) | More accurate calculation |
| Function encapsulation | O(1) | O(1) | Reusable code |
Use
math.pi for a more precise value of pi instead of 3.14159.Forgetting to convert input to float causes errors when calculating area.