Python realizes calculating the circumference and area of a circle

Requirement: Input the radius of the circle, calculate the circumference and area of ​​the circle, keep the result to two decimal places, and check the validity of the input of the radius of the circle

Implementation code:

# 全局变量
PI = 3.1415926


def input_num():
    '''
    输入一个有效的数字
    :return: 返回输入有效的数字
    '''
    # 使用循环实现,如果输入的无效就提示重新输入
    while True:
        # 提示输入圆的半径 (默认情况下,input输入返回的是字符串 '100')
        radius_str = input('请输入圆的半径:')
        # 使用异常处理
        try:
            radius = float(radius_str)
            # 返回
            return radius
        except:
            print('输入的半径无效,请重新输入!')


def get_area(radius):
    '''
    计算圆的面积
    :param radius: 圆的半径
    :return: 返回圆的面积
    '''

    # 返回圆的面积
    return PI * radius * radius


def get_perimeter(radius: float):
    '''
    计算圆的周长
    :param radius: 圆的半径
    :return: 返回圆的周长
    '''
    # 返回圆的周长
    return 2 * PI * radius


# main函数:程序的入口
if __name__ == '__main__':
    # 调用函数,提示输入半径,返回一个符合要求的值
    radius = input_num()
    # 输出 -- 通过占位符实现保留两位小数
    print('圆的周长为:%.2f' % get_perimeter(radius))
    print('圆的面积为:%.2f' % get_area(radius))

Guess you like

Origin blog.csdn.net/weixin_49981930/article/details/128680136