Use Python to create an application to calculate the area and circumference of a circle

Document 对象参考手册Python3 Examples

We will write a simple application in Python to calculate the area and circumference of a circle. The user will input the radius of the circle, and the program will output the area and circumference of the circle.

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)
    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'smathmodule, so as to usemath.pito obtain the value of pi.
  2. calculate_area(radius): Define a function to calculate the area of a circle, the formula isπ * r^2。
  3. calculate_circumference(radius): Define a function to calculate the circumference of a circle, the formula is2 * π * r。
  4. main(): The main function, responsible for obtaining the radius entered by the user, calling the above two functions to calculate the area and circumference, and outputting the results.
  5. if __name__ == "__main__":: Ensure that the script only executes when run directlymain()function.

Output result: Assuming the user enters a radius of 5, the program will output:

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

Document 对象参考手册Python3 Examples

Other Extensions