python函数运用

函数

函数的好处:函数更方便,复用,可以在多个场景下用

函数用来:实现一个功能.函数理解成一个工具,遇到了问题把这个工具拿来用

直接函数调用

def get_pi():
    import random

    count = 0
    for i in range(10000):
        x, y = random.random(), random.random()
        dist = pow((x - 0) ** 2 + (y - 0) ** 2, 0.5)

        if dist < 1:
            count += 1

    print(4 * count / 10000)
#
get_pi()

带参数的函数调用

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(10)
get_pi(100)
get_pi(1000)
get_pi(10000)
get_pi(100000)

带返回值的函数调用

def add_sum(num):

    count = 0
    for i in range(1, num):
        count += i

    return count


res1= add_sum(101)
print('res1:',res1)
res2 = add_sum(1001)
print('res2:',res2)
res3 = add_sum(10001)
print('res3:',res3)

作  者:豆瓣酱瓣豆
出  处:https://www.cnblogs.com/chenziqing/
查看其它博文请点击:https://www.cnblogs.com/chenziqing/
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!

微信:

猜你喜欢

转载自www.cnblogs.com/chenziqing/p/11206637.html