Exercise 10
Write a Python algorithm that prompts the user to enter the radius of a circle and calculates its area and perimeter, and then displays the results.
Solution
import math
# Prompt the user to enter the radius of the circle
radius = float(input("Enter the radius of the circle: "))
# Calculate the area and perimeter of the circle
area = math.pi * radius ** 2
perimeter = 2 * math.pi * radius
# Display the results
print(f"The area of the circle is {area:.2f}")
print(f"The perimeter of the circle is {perimeter:.2f}")
Explanation:
- We first import the math module: to use its pi constant.
- Then we prompt the user to enter the radius of the circle: and store it in the radius variable.
- We then use the radius: to calculate the area and perimeter of the circle using the formulas pi*r2 and 2*pi*r, respectively.
- Finally: we display the results using the print function, with the .2f format specifier to round the results to two decimal places.
Younes Derfoufi
CRMEF OUJDA
[…] Exercise 10 || Solution […]