python学习笔记之函数

函数

  • 不带参数没有返回值的函数

    # 圆的面积公式: Πr^2  ,当r=1的时候,圆的面积就是Π
    def get_pi()
        import random
    
        count = 0
        for i in range(1000000):
            x,y = random.random(),random.random()
            dist = pow((x-0)**2+(y-0)**2,0.5)
    
            if dist < 1:
                count +=1
    
        print(4*count/1000000)
    
    get_pi()		# 直接调用该函数
    
  • 带参数没有返回值的函数

    # 圆的面积公式: Πr^2  ,当r=1的时候,圆的面积就是Π
    def get_pi(num)
        import random
    
        count = 0
        for i in range(num):
            x,y = random.random(),random.random()
            dist = pow((x-0)**2+(y-0)**2,0.5)
    
            if dist < 1:
                count +=1
    
        print(4*count/num)
        
    get_pi(1000000)		# 调用该函数并传参
    
  • 带参数有返回值的函数

    def add_sum(num):	# 求和函数
    
        count = 0
        for i in range(1, num+1):
            count += i
    
        return count
    
    res1= add_sum(100)	# 调用函数并传参,得到返回值
    print('res1:',res1)
    

posted @ 2019-07-24 08:47  正在学习的Barry  阅读(187)  评论(0编辑  收藏  举报
-->