python实例

我们将使用 Python 编写一个简单的应用程序来计算圆的面积和周长。用户将输入圆的半径,程序将输出圆的面积和周长。

实例

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("请输入圆的半径: "))
    area = calculate_area(radius)
    circumference = calculate_circumference(radius)
    print(f"圆的面积为: {area:.2f}")
    print(f"圆的周长为: {circumference:.2f}")
    
if __name__ == "__main__":
    main()

代码解析:

  1. import math:导入 Python 的 math 模块,以便使用 math.pi 来获取圆周率的值。

  2. calculate_area(radius):定义一个函数来计算圆的面积,公式为 π * r^2

  3. calculate_circumference(radius):定义一个函数来计算圆的周长,公式为 2 * π * r

  4. main():主函数,负责获取用户输入的半径,调用上述两个函数计算面积和周长,并输出结果。

  5. if __name__ == "__main__"::确保脚本在直接运行时才会执行 main() 函数。

  6. 输出结果: 假设用户输入的半径为 5,程序将输出:

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