Create an Application to Compute the Area and Circumference of a Circle in Python
We will write a simple Python application that computes the area and circumference of a circle. The user enters the radius and the program outputs the area and circumference.
Example
import
math
def
calculate_area
(
radius
)
:
return
math
.
pi
- radius **
2
def
calculate_circumference
(
radius
)
:
return
2
math
.
pi
- radius
def
main
(
)
:
radius
=
float
(
input
(
"Please enter the radius of the circle: "
)
)
area
=
calculate_area
(
radius
)
circumference
=
calculate_circumference
(
radius
)
(
f
"The area of the circle is: {area:.2f}"
)
(
f
"The circumference of the circle is: {circumference:.2f}"
)
if
name
==
"main"
:
main
(
)
Code analysis:
import math: import Python'smathmodule so thatmath.pican be used to get the value of pi.calculate_area(radius): define a function to compute the area of a circle, with the formulaπ * r^2。calculate_circumference(radius): define a function to compute the circumference of a circle, with the formula2 * π * r。main(): the main function obtains the radius from user input, calls the two functions to compute the area and circumference, and prints the results.if __name__ == "__main__":: ensure the script only runs when executed directlymain()function in Vue 3.
Output: assuming the user enters a radius of 5, the program prints:
请输入圆的半径: 5
圆的面积为: 78.54
圆的周长为: 31.42
Python3 Examples