2018.12.11——函数

一、定义一个函数:

def test(x):
    'the function definitions'
    y=x+1
    return y_
print(test)

输出结果:是一个内存地址:

如何执行函数?

1.带参数x

def test(x):
    'the function definitions'
    y=x+1
    return y

a=test(3)
print(a)

#输出结果:4

2.不带参数x:

def test():
    'the function definitions'
    x=3
    y=x+1
    return y

a=test()
print(a)

#输出结果:4

二、函数与过程的区别:

1.函数:

def test01():
    msg='hello'
    return(msg)
a1=test01()
print(a1)

#输出结果:hello

2.过程:

def test02():
    msg='hello'
    #没有返回值
a2=test02()
print(a2)

#输出结果:None

 三、注意:

1.return可以指定返回的值

例如:

def test01():
    msg='hello'
    return 1,2,3,['dda']
a1=test01()
print(a1)


#输出结果:(1,2,3,['dda'])    返回的是一个元组(容器类型,可以存放多个值)

2.函数碰到了return即结束了:

def calc(x,y):
    p=x+y
    return x
    return p  #第二个return不起作用,因为从上到下第一个return运行后函数就关闭了。
c=calc(3,5)
print(c)

#输出结果:3

四、位置参数与关键字参数:

def test(x,y,z):
    print(x)
    print(y)
    print(z)
# test(1,3,y=2)#报错
test(1,3,z=2)#可以

五、默认函数

六、参数组——可变参数值

def test(x,*args):
    print(x)
    print(args)
# test(1,**{'ppp':123,'name':'sdh'})——报错
# test(1,*{'ppp':123,'name':'sdh'})
# 输出:
# 1
# ('ppp','name',)
test(1,*['ppp',123,'name','sdh'])
# 输出:
# 1
# ('ppp',123,'name','sdh')

猜你喜欢

转载自www.cnblogs.com/lijialun/p/10101448.html