- 局部变量
x=50 def func(x): #global x print('x is',x) x=2 print('changed local x to',x)
在函数外部x不会改变,若要改变x需要在函数开头申明global
- 重复输出同一字符串
#输出三次hello print('hello'*3)
- 默认参数
def func(a,b=5,c=10): print('a is',a,'and b is',b,'and c is',c)
默认参数只能出现在参数列表的末尾,不能出现在非默认参数前面。
- pass的作用
def func(): pass
一个没写好的函数可以先这样定义留着后面写
- 可变参数
def total(a=5,*numbers,**phonebook): print(a) #遍历元组中的所有项 for i in numbers: print(i) for k,v in phonebook.items(): print(k,v) print(total(10,1,2,3,jack=1123,john=2231,inge=1560)
从10后面开始的1,2,3保存在numbers这个元组中,从3后面开始的jack=1123等保存在phonebook这个字典中(注意字典中要遍历键和值需要用上述语句,否则只会遍历键)
-
文档字符串
def print_max(x,y): '''Prints the maximum of two numbers. The two values must be integers.''' x=int(x) y=int(y) if x>y: print(x,'is maximum') else: print(y,'is maximum') print_max(3,5) print(print_max.__doc__)#也可以用help(print_max)
文档字符串是用来给函数解释说明的字符串,约定文档字符串在第一行以大写字母开头,以句号结尾。第二行为空行,第三行为详细的解释说明。
byte of python笔记——函数篇
猜你喜欢
转载自blog.csdn.net/why12345678901/article/details/81407208
今日推荐
周排行