这一章讲的函数,函数的调用,函数的参数,python中函数的参数有
1
位置参数
调用时候必须传入一个参数。
2
默认参数
调用的时候可以不必须传入这个参数。
但是定义的时候要赋予一个默认值,这个东西更适合我们处理某个问题时候
经常有某个值不需要改变
这里有个坑:
默认参数必须只想不变的 对象,可以是int float str
等等
元组是个不变的东西,但是他不是对象,但是你可以让他作为默认参数。这
很神奇。
当我们让列表做默认参数的时候
def add_end(L = [1,2,3]):
L.append('END')
return L
print(add_end([1,2,3]))
print(add_end(['x','y','z']))
print(add_end())
print(add_end())
print(add_end())
def add_end(L=None):
if L is None:
L = []
L.append('END')
return L
print(add_end())
print(add_end())
print(add_end())
print(add_end())
当我们用列表做默认参数的时候,L.append()似乎给我们的列表一直在添加值
这是因为默认参数的只想是不变的 但是L是一个变量,L的内容改了,那么默认参数的内容
自然会发生变化了。
重点:我们的指向不会变,但是指向的列表变化,会导致我们的结果变化。
3.可变参数
顾名思义 参数的 个数不确定 是可以改变的 可以是123456789还可以是0
# -*- coding:utf-8 -*-
def power2(x,n):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
print(power2(5,3))
def calc(numbers):
sum = 0
for n in numbers:
sum = sum + power2(n,2)
return sum
print(calc((1,3,5,7,9)))
print(calc([1,3,5]))
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + power2(n,2)
return sum
print(calc(1,3,5))
print(calc(1,5))
print(calc())
nums = [1,2,3]
print(calc(nums[0],nums[1],nums[2]))
print(calc(*nums))
这个也是练习题的答案所在。
关键字参数:
可变参数允许传入0 或者任意个参数,这些可变参数在函数调用时自动组装为一个tuple
关键字参数还可以传入任意个含有参数名的参数。关键字参数在函数内部自动组装
成为一个dict
总结一下*num 接收的是可变数目的参数 tuple这种就可以传进来。
** nums 接受的是关键字参数,kw是一个dict
再用*num的时候我们可以直接传func(1,2,3)python会自己组装成tuple 。
也可以先组装list或者tuple 通过*num传入func(*1,2,3))
关键字参数也是一样可以直接func(a = 1, b = 2) 也可以先组装成dict用**num
: func(**{'a':1,'b':2})
*args 和**kw
是python的习惯写法,我们最好使用习惯用法。
命名的关键字参数是为了限制调用者可以传入的参数名,同时提供默认值。
第一命名关键字参数在没有可变参数的情况下要写分隔符*,否则定义的是位置参数。
函数的递归:
递归很简单
def fact(n):
if n == 1:
return 1
return n * fact(n-1)
print(fact(5))
#尾递归,第一个fact return给fact_iter()
def fact1(n):
return fact_iter(n,1)
def fact_iter(num,product):
if num == 1:
return product
return fact_iter(num - 1,num * product)
print(fact1(5))
def factt(inter):
return factt_iter(inter,product = 1)
def factt_iter(num , product):
if num == 1:
return product
return factt_iter(num - 1,product * num)
print(factt(6))
尾递归我认为需要特殊说明。首先是两个函数,然后第二个函数
return的两个参数(被递归数,结果)
尾递归可以节省栈的空间。而且不会栈溢出(如果解释器进行了优化)
def my_abs(x,y): if not isinstance(x,(int,float)): raise TypeError('bad operand type') if x > 0: return x,y else: return -x,-y
这是另一个.py,用来被调用的函数
------------------------------------------------
# -*- coding:utf-8 -*-
from abstest import my_abs
import math
n1 = 255
n2 = 1000
print(hex(n1))
print(hex(n2))
print(my_abs(-1,-2))
age = 16
if age >= 18:
pass
def nop():
pass
def move(x,y,step,angle = 0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx , ny
x ,y = move(100,100,60,math.pi/6)
print(x,y)
r = move(100,100,60,math.pi/6)
print(r)
#the result which returned is a tuple
def quadratic(a,b,c):
if (a == 0) or (b == 0):
print('error')
return
delta = math.sqrt(b*b-4*a*c)
x1 = (-b + delta)/(2*a)
x2 = (-b - delta)/(2*a)
return x1,x2
result = quadratic(1,3,-4)
print(result)
result = quadratic(2,3,1)
print(result)
result = quadratic(0,3,1)
print(result)
def power(x):
return x*x
print(power(3))
def power2(x,n):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
print(power2(5,3))
def power3(x,n = 2):
result = 1
for i in range(n):
result = result * x
return result
print(power3(5,4))
def enroll(name,gender):
print('name',name)
print('gender',gender)
return 'yes'
print(enroll('Sarah','F'))
def enroll1(name,gender,age = 6,city = 'qinhuangdao'):
print('name',name)
print('gender',gender)
print('age',age)
print('city',city)
enroll1('yangchun','dasi','22')
enroll1('yangchun','dayi',city='beijing')
def add_end(L = [1,2,3]):
L.append('END')
return L
print(add_end([1,2,3]))
print(add_end(['x','y','z']))
print(add_end())
print(add_end())
print(add_end())
def add_end(L=None):
if L is None:
L = []
L.append('END')
return L
print(add_end())
print(add_end())
print(add_end())
print(add_end())
def calc(numbers):
sum = 0
for n in numbers:
sum = sum + power2(n,2)
return sum
print(calc((1,3,5,7,9)))
print(calc([1,3,5]))
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + power2(n,2)
return sum
print(calc(1,3,5))
print(calc(1,5))
print(calc())
nums = [1,2,3]
print(calc(nums[0],nums[1],nums[2]))
print(calc(*nums))
def person(name,age,**kw):
print('name',name,'age',age,'other',kw)
person('Michael',36)
person('yangchun',22,city = 'TianJin',job = 'Engineer')
extra = {'city':'beijing','job':'engineer'}
extra2 = {'city':'YJUT','job':'Student'}
person('Jack',24,city = extra['city'],job = extra['job'])
person('Jack',24,**extra2)
def person(name,age,**kw):
if 'city' in kw:
pass
if 'job' in kw:
pass
print('name:',name,'age',age,'other',kw)
person('Jack',222,city = 'beijing',addr = 'chaoyang',zipcode = 123456)
def person(name ,age ,*,city = 'beijing',job):
print(name,age,city,job)
person('Jack', 222, job = 'Engineer')
def person(name, age, *,city ="beijing", job):
pass
person('Jack', 222,job = 'Engineer')
def f1(a,b,c= 0,*args,**kw):
print('a = ',a,'b = ',b,'c = ',c,'args = ',args,'kw = ',kw)
def f2(a,b,c = 0,*,d,**kw):
print('a = ',a,'b = ',b,'c = ',c,'d = ',d,'kw = ',kw)
f1(1,2)
f1(1,2,c = 3)
f1(1,2,3,'a','ab')
f1(1,2,3,'a','b',x = 99)
f2(1,2,d = 99,ext = None)
args = (1,2,3,4)
kw = {'d':99,'x':'#'}
f1(*args,**kw)
args = (1,2,3)
kw = {'d': 88,'x':'#'}
f2(*args,**kw)
def product(x,y=1,d =1,c = 1):
return x*y*d*c
print(product(5,6,7,9))
def fact(n):
if n == 1:
return 1
return n * fact(n-1)
print(fact(5))
#尾递归,第一个fact return给fact_iter()
def fact1(n):
return fact_iter(n,1)
def fact_iter(num,product):
if num == 1:
return product
return fact_iter(num - 1,num * product)
print(fact1(5))
def factt(inter):
return factt_iter(inter,product = 1)
def factt_iter(num , product):
if num == 1:
return product
return factt_iter(num - 1,product * num)
print(factt(6))
#练习
#以下函数允许计算两个数的乘积,请稍加改造,变成可接收一个或多个数并计算乘积:def product(x, y):
# return x * y
def product(*num):
sum = 1
for n in num:
sum = sum * n
return sum
print(product(1,3,5))