函数
函数就是用来实现一个功能的,把函数理解成一个工具,遇到问题把这个工具拿来用
函数的好处:函数更方便,复用,可以在多个场景使用
eg:
def get_pi(num):
import random
count = 0
for i in range(num):
x,y = random.random(),random.random()
d = pow(x**2+y**2,0.5)
if d < 1:
count += 1
print(count/num*4)
get_pi(1000)
1.带参数的函数
name = 'nick'
name.split()
2.带返回值的函数
def add_sum(num):
count = 0
for i in range(1,num):
count += i
return(count)
res1 = add_sum(101)
print("res1:",res1) # res1:5050
res2 = add_sum(1001)
print("res2:",res2) # res2:500500
res3 = add_sum(10001)
print("res3:",res3) # res3:50005000