Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Create an Application to Compute the Area and Circumference of a Circle in Python

Create an Application to Compute the Area and Circumference of a Circle in Python

Document Object Reference Manual Python3 Examples

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

2

def

calculate_circumference

(

radius

)

:

   

return

2

math

.

pi

def

main

(

)

:

    radius

=

float

(

input

(

"Please enter the radius of the circle: "

)

)

    area

=

calculate_area

(

radius

)

    circumference

=

calculate_circumference

(

radius

)

   

print

(

f

"The area of the circle is: {area:.2f}"

)

   

print

(

f

"The circumference of the circle is: {circumference:.2f}"

)

if

name

==

"main"

:

    main

(

)

Code analysis:

  1. import math: import Python's math module so that math.pi can be used to get the value of pi.
  2. calculate_area(radius): define a function to compute the area of a circle, with the formula π * r^2。
  3. calculate_circumference(radius): define a function to compute the circumference of a circle, with the formula 2 * π * r。
  4. main(): the main function obtains the radius from user input, calls the two functions to compute the area and circumference, and prints the results.
  5. if __name__ == "__main__":: ensure the script only runs when executed directly main() function in Vue 3.

Output: assuming the user enters a radius of 5, the program prints:

请输入圆的半径: 5
圆的面积为: 78.54
圆的周长为: 31.42

Document Object Reference Manual Python3 Examples