Use Python to create an application to calculate the area and circumference of a circle
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()
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:
import math: Import Python'smathmodule, so as to usemath.pito obtain the value of pi.calculate_area(radius): Define a function to calculate the area of a circle, the formula isπ * r^2。calculate_circumference(radius): Define a function to calculate the circumference of a circle, the formula is2 * π * r。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.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.42Other Extensions
Python3 Examples