python3基础之函数

一、举例

In [10]:

print("hello") # 打印
hello

In [11]:

round(1.5) # 小数提取

Out[11]:

2

二、函数特性

2.1.功能性

2.2.隐藏细节

2.3.避免编写重复的代码

2.4 组织代码 自定义函数

三、函数的编写

3.1 函数定义

In [12]:

def fun(a):
    return a
print(fun(1))
1

函数的参数和返回值都一款没有

三、函数的注意事项

3.1 函数名称不要用内置函数名

In [ ]:

def print(code):
    pass
print(1) # 这里会覆盖掉原来内置print的定义

注意:这个函数测试的时候最后运行,否则会造成后面的打印函数都时效

3.2 没有返回值结果返回None

In [13]:

def fun():
    pass
print(fun())
None

3.3 函数碰到return后不会执行

In [14]:

def fun2():
    return 0
    print(1)
print(fun2()) # 函数中的print 没有执行
0

3.4 返回多个值时可以用序列解包的方式

In [15]:

def fun3():
    return 0,1
a,b = fun3()
print(a,b)
0 1

四、函数的参数

4.1.必须参数

In [16]:

def fun4(x,y):
    pass
fun4(1,2)

x,y为形参,1,2为实参

4.2.关键字参数(无需考虑函数参数顺序)

In [17]:

def fun5(x,y):
    pass
fun5(y=2,x=1)

4.3.默认参数

In [18]:

def fun5(x=1,y=2):
    return x,y
a,b =fun5(y=2,x=1)
print(a,b)
a,b =fun5(y=1,x=2)
print(a,b)
a,b =fun5()
print(a,b)
1 2
2 1
1 2

五、git地址

https://coding.net/u/RuoYun/p/Python-Programming-Notes/git/tree/master/0.basics/6.function

猜你喜欢

转载自blog.csdn.net/u013584315/article/details/81180476