Credit: Lisa Yan
File: area_calculator.py
Write a program that reads in a float radius from the user and then prints out the associated area of the circle. If the radius is invalid (negative or zero), print an error. Here are three example runs of the program:
Please enter a circle radius: 5
The area of your circle is: 78.53981633974483
Please enter a circle radius: -3
Error! You entered an invalid radius.
Please enter a circle radius: 0
Error! You entered an invalid radius.
Write code that asks the user for a radius, and then outputs the area of the corresponding circle.
Given the radius (sometimes called r
) of a circle, you can calculate the area of the circle to be, π times the radius squared (see Wikipedia).
$$\text{Area} = \pi \cdot \text{radius} ^2$$
What is pi? π (pi) is a mathematical constant which Python has stored in the math library. In your project we included the line import math
which gets you access to the math library. Don't delete this line. To access π inside your main()
function, you can use math.pi
. For example, if we wanted to print out π to the console:
def main():
print(math.pi)
The radius value which a user inputs should be positive. It doesn't make sense to calculate the area if the radius is zero or negative! If they enter an "invalid" radius print out "Error! You entered an invalid radius."
Try putting all of your code in a while True loop
while True:
# your code
so that your program repeatedly asks the user for a radius and repeatedly calculates the area.
Here is an example run:
Please enter a circle radius: 5
The area of your circle is: 78.53981633974483
Please enter a circule radius -2
Error! You entered an invalid radius.
Please enter a circle radius: 9
The area of your circle is: 254.4690049412345
Please enter a circle radius: