函数的定义
来源:互联网 发布:windows ce 6.0 编辑:程序博客网 时间:2024/05/22 07:05
1.函数的一般形式
定义一个函数需要以下规则:
函数代码块以 def 关键词开头,后接函数标识符名称和圆括号()
任何传入参数和自变量必须放在圆括号中间,圆括号中间可以用于自定义参数。
函数的第一行语句可以选择性的使用文档字符串-用于存放函数说明
函数内容以冒号起始,并且缩进
return[表达式] 表示函数结束,不带表达式的return,返回None
创建一个函数:
def fun(x,y): print ('x = {0}'.format(x)) print ('y = {0}'.format(y)) return x+yx =1y =3z = fun(x,y)print z返回为:
x = 1y = 34
def是函数的关键字,函数的格式
def 后面就是函数名字,这个可以自定义
括号里面传递的是函数的参数,改参数在函数中都可以使用
return 是表带当我们调用函数的时候返回的结果。
2.函数的各种类型参数
1.实例1:
def fun1(a,b=0): print a print bfun1(1)结果为:
10如果把fun1(1)改为fun1(1,2),结果为:
12fun1(a,b=0)其实是给b 设置了一个默认参数,如果没有给b设置参数,b就是0,设置了参数,优先使用设置的实参。
2.参数为tuple, man(m,*args)
def fun2(a,b,*c): print a print b print 'leng c is %d' % len(c) print cfun2(1,2,3,4,5,6)结果为:
12leng c is 4(3, 4, 5, 6)也可以这样写
def fun2(a,b,*c): print a print b print 'leng c is %d' % len(c) print c#fun2(1,2,3,4,5,6)tub = ('hello','world')fun2(1,2,*tub) #用星号
3.参数为字典,man(m,**args) 两个星号
def fun3(a,**b): print(a) print(b) for x in b: print x + ':' + str(b[x])fun3(100,x='hello',y='你好')结果为:
100{'y': '\xe4\xbd\xa0\xe5\xa5\xbd', 'x': 'hello'}y:你好x:hello也可以用**去写
n3(a,**b): print(a) print(b) for x in b: print x + ':' + str(b[x])fun3(100,x='hello',y='你好')args = {'1':'abc','b':'hello'}fun3(100,**args)结果为:
100{'y': '\xe4\xbd\xa0\xe5\xa5\xbd', 'x': 'hello'}y:你好x:hello100{'1': 'abc', 'b': 'hello'}1:abcb:hello
阅读全文
0 0
- 用户定义的函数
- 新的函数定义
- java函数的定义
- inet_ntop函数的定义
- 虚函数的定义
- 虚函数的定义
- 函数的定义格式
- WinMain函数的定义
- 函数的副作用定义
- 虚函数的定义
- 4.2、函数的定义
- 函数指针的定义
- python的函数定义
- 虚函数的定义
- 母函数的定义
- 凸凹函数的定义
- 函数的定义
- 函数的定义
- mysql之常用函数集锦
- linux中的定时延时任务
- Action中使用Servlet对象
- Fastjson 自定义 json 的 值输出格式
- Python With Visual Studio Code – A 5 Step Guide
- 函数的定义
- 646. Maximum Length of Pair Chain(动态规划 vs 贪心)
- 【NOIP2017提高A组冲刺11.1】总结
- framebuffer简介与应用
- poj 3661(区间dp)
- 【单调队列】BZOJ1047(HAOI2007)[理想的正方形]题解
- 基于javaMail发送邮件的实现
- ios MBProgressHud 自定义背景 背景色 标题颜色
- Coreldraw绘画看了这个才算是真正明白了什么叫绘图