函数
1. 函数的创建和调用
def calc(a,b):
c=a+b
return c
result=calc(10,20)
print(result)
res=calc(b=1,a=20)
print(res)
2.函数的参数传递
def fun(arg1,arg2):
print('arg1',arg1)
print('arg2',arg2)
arg1=100
arg2.append(10)
print('arg1',arg1)
print('arg2',arg2)
n1=11
n2=[22,33,44]
print('n1',n1)
print('n2',n2)
fun(n1,n2)
print('n1',n1)
print('n2',n2)
3.函数的返回值
3.1判断奇偶
'''
print(bool(0))#0的布尔值为False
print(bool(8))#其余数字为True
'''
def fun(num):
odd=[]
even=[]
for i in num:
if i%2:
odd.append(i)
else:
even.append(i)
return odd,even
3.2函数的调用
lst=[10,29,34,23,44,53,55]
print(fun(lst))
def fun1():
print('hello')
fun1()
def fun2():
return 'hello'
res=fun2()
print(res)
def fun3():
return 'hello','world'
print(fun3())
4.函数的参数定义
def fun(a,b=10):
print(a,b)
fun(100)
fun(20,30)
print('hello',end='\t')
print('world')
def fun(*args):
print(args)
'''(10,)
(10, 30, 40)'''
fun(10)
fun(10,30,40)
def fun1(**args):
print(args)
'''{'a': 10}
{'a': 20, 'b': 30, 'c': 40}'''
fun1(a=10)
fun1(a=20,b=30,c=40)
print('hello','world','ptyhon')
'''def fun2(*args,*a):#个数可变位置参数只能是一个
pass'''
'''def fun2(**args,**args):#个数可变的关键字参数只能是一个
pass'''
def fun2(*args1,**args2):
pass
'''def fun3(**args1,*args2):#关键字参数在位置参数之前,报错
pass'''
def fun(a,b,c):
print('a=',a)
print('b=',b)
print('c=',c)
fun(10,20,30)
lst=[6,66,666]
fun(*lst)
print('------------------------')
fun(a=700,c=900,b=800)
dic={'a':111,'b':222,'c':333}
fun(*dic)
fun(**dic)
'''a= 10
b= 20
c= 30
a= 6
b= 66
c= 666
------------------------
a= 700
b= 800
c= 900
a= a
b= b
c= c
a= 111
b= 222
c= 333
进程已结束,退出代码0
'''
def fun(a,b=10):
print('a=',a)
print('b=',b)
def fun2(*args):
print(args)
def fun3(**args2):
print(args2)
fun2(99,88,77,66)
fun3(a=11,b=22,c=33,d=44,e=55)
def fun4(a,b,c,d):
print('a=',a)
print('b=',b)
print('c=',c)
print('d=',d)
fun4(10,20,30,40)
fun4(a=10,b=20,c=30,d=40)
fun4(10,20,c=30,d=40)
def fun5(a,b,*,c,d,**args):
pass
def fun6(*args,**args2):
pass
def fun7(a,b=10,*args,**args2):
pass
5.变量的作用域
def fun(a,b):
p=a+b
print(p)
name='你好'
print(name)
def fun2():
print(name)
fun2()
def fun3():
global age
age=20
print(age)
fun3()
print(age)
6.递归函数
def fac(n):
if n==1:
return 1
else:
return n*fac(n-1)
print(fac(6))
def fib(n):
if n==1:
return 1
elif n==2:
return 1
else:
return fib(n-1)+fib(n-2)
print(fib(9))
for i in range(1,10):
print(fib(i),end='\t')
|