函数
python也分形参实参
函数文档(突然发现tab是好用的)
def myfirstfun(name):
'xxxx'
#xxxxx
print(name)
>>> myfirstfun(x)
SyntaxError: invalid character in identifier
>>> myfirstfun('x')
x
>>> myfirstfun.__doc__
'xxxx'
>>> help(myfirstfun)
Help on function myfirstfun in module __main__:
myfirstfun(name)
xxxx
>>> print.__doc__
"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile: a file-like object (stream); defaults to the current sys.stdout.\nsep: string inserted between values, default a space.\nend: string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream."
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
>>>
关键字参数
>>> tell('misszhou','让编程编织梦想')
misszhou让编程编织梦想
>>> tell(wors='words',name='misszhou')
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
tell(wors='words',name='misszhou')
TypeError: tell() got an unexpected keyword argument 'wors'
>>> tell(words='words',name='misszhou')
misszhouwords
默认参数
>>> def saysome(name='name',word='word'):
print(name+word)
>>> saysome
<function saysome at 0x000000A74A7969D8>
>>> saysome()
nameword
收集参数(这玩意别的语言没有,类C语言有可变参数啊)print的实现
>>> def test(*par):
print('len',len(par))
print(par[0])
>>> test(1,2,3,4)
len 4
1
>>> def test(*par,exp=8)
SyntaxError: invalid syntax
>>> def test(*par,exp=8):
print('len:',len(par),exp)
print('第二个参数为',par[1])
>>> test(1,2,3,4)
len: 4 8
第二个参数为 2
函数与过程
python可以返回多个值(通过列表打包呗)
>>> def back():
return 1,'misszhou'
>>> back()
(1, 'misszhou')
python也分全局变量/局部变量
一段神奇的代码
def discount(price,rate):
fin_price=price*rate
# print('这里试图打印全局变量old_price:',old_price)
old_price=50
print('1修改后oldprice的值',old_price)
return fin_price
old_price=float(input('请输入原价:'))
rate=float(input('请输入折扣;'))
new_price=discount(old_price,rate)
print('2修改后oldprice的值',old_price)
print('折扣后价格:',new_price)
请输入原价:100
请输入折扣;0.9
1修改后oldprice的值 50
2修改后oldprice的值 100.0
折扣后价格: 90.0
为什么呢?在函数里面的那个是新创建的局部变量!!不是原来的那个全局变量
我要是想在函数里面修改全局变量,也可以嵌套定义
内嵌函数和闭包
global关键字(这玩意和php一样啊=w=)
>>> count=5
>>> def myfun()
SyntaxError: invalid syntax
>>> def myfun():
count=10
print(count)
>>> def myfun()
SyntaxError: invalid syntax
>>> myfun()
10
>>> print(count)
5
>>> def myfun():
global count
count=10
print(10)
SyntaxError: invalid character in identifier
>>> def myfun():
global count
count=10
print(10)
>>> def myfun():
global count
count=10
print(count)
>>> def myfun()
SyntaxError: invalid syntax
>>> myfun()
10
>>> print(count)
10
函数嵌套
>>> def fun1():
print('fun1')
def fun2():
print('fun2')
fun2()
>>> fun1()
fun1
fun2
>>> fun2()
Traceback (most recent call last):
File "<pyshell#68>", line 1, in <module>
fun2()
NameError: name 'fun2' is not defined
>>> fun1().fun2()
fun1
fun2
Traceback (most recent call last):
File "<pyshell#69>", line 1, in <module>
fun1().fun2()
AttributeError: 'NoneType' object has no attribute 'fun2'
闭包(这玩意js有啊)
>>> def funx(x):
def funy(y):
return x*y
return funy
>>> i=funx(8)
>>> i
<function funx.<locals>.funy at 0x0000004A51346A60>
>>> type(i)
<class 'function'>
>>> i(5)
40
>>> funx(4)(4)
16
>>> funy(8)
Traceback (most recent call last):
File "<pyshell#80>", line 1, in <module>
funy(8)
NameError: name 'funy' is not defined
>>> def fun1():
x=5
def fun2():
x*=x
return x
return fun2()
>>> fun1()
Traceback (most recent call last):
File "<pyshell#88>", line 1, in <module>
fun1()
File "<pyshell#87>", line 6, in fun1
return fun2()
File "<pyshell#87>", line 4, in fun2
x*=x
UnboundLocalError: local variable 'x' referenced before assignment
>>> def fun1():
x[0]=5
def fun2():
x[0]*=x[0]
return x[0]
return fun2()
>>> fun1()
Traceback (most recent call last):
File "<pyshell#91>", line 1, in <module>
fun1()
File "<pyshell#90>", line 2, in fun1
x[0]=5
NameError: name 'x' is not defined
>>> def fun1():
x=[5]
def fun2():
x[0]*=x[0]
return x[0]
return fun2()
>>> fun1()
25
>>> def fun1():
x=5
def fun2():
nonlocal x
x*=x
return x
return fun2()
>>> fun1()
25
lambda表达式
参数:返回值
>>> x=lambda x,y:x+y
>>> print(x)
<function <lambda> at 0x0000004A51346EA0>
>>> x(3,4)
7
这玩意在js里面不也有么……
lambda表达式的作用
省下定义函数的作用、不需要考虑函数名、省得函数阅读跳到开头定义部分
filter()过滤器
help(filter)
Help on class filter in module builtins:
class filter(object)
| filter(function or None, iterable) --> filter object
|
| Return an iterator yielding those items of iterable for which function(item)
| is true. If function is None, return the items that are true.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)<pre name="code" class="python">>>> def odd(x):
return x%2
>>> temp=range(10)
>>> show=filter(odd,temp)
>>> list(show)
[1, 3, 5, 7, 9]
| Return state information for pickling.filter(None,[1,0,False,True])<filter object at 0x0000004A5135B240>>>> list(filter(None,[1,0,False,True]))
[1, True]
默认把一切非正的过滤掉
自定义:
>>> def odd(x):
return x%2
>>> temp=range(10)
>>> show=filter(odd,temp)
>>> list(show)
[1, 3, 5, 7, 9]
学以致用精简一下
>>> list(filter(lambda x:x%2,range(10)))
map()
映射
list(map(lambda x:x%2,range(10)))
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
递归
可以人为规定递归层数
import sys
sys.setrecursionlimit(10000)
输出阶乘
def func(num):
if(num==1):
return 1
return num*func(num-1)
num=int(input())
print(func(num))
递归的斐波那契
def fun(n):
if(n==3):
return 2
elif(n==2):
return 1
return fun(n-1)+fun(n-2)
print(fun(12))
汉诺塔
def hano(n,x,y,z):
if(n==1):
print(x,"-->",z)
return
hano(n-1,x,z,y)
print(x,"-->",z)
hano(n-1,y,x,z)
n=int(input())
hano(n,'x','y','z')