Python3基础-函数

一、函数是分类

1、内置函数

Python解释器已经定义好了的函数即为内置函数;如len(),sum(),max()

2、自定义函数 根据自己的需求,制定好函数来实现某种功能
======================================================

使用函数的好处
1、代码重用
2、保持一致性,易维护
3、可扩展性

二、定义函数

1、如何自定义函数

 1 #python中函数定义方法
 2 def 函数名(参数1,参数2,参数3,...):
 3     '''注释'''
 4     函数体
 5     return 返回的值
 6 
 7 #函数名要能反映其意义
 8 
 9 def:定义函数的关键字
10 test:函数名
11 ():内可定义的形参
12 函数体:泛指代码块或者程序处理的逻辑
13 returun:定义返回值
14 
15 调用运行:可以带参数也可以不带
16 函数名()
#登录密码错误,有2次重新登录机会  带参数
def auth(username,passwd,count,sum_c):
    while sum_c > 1:
        if username == 'susu' and passwd == '123456':
            return 1
            break
        sum_c  = sum_c - count
        print("账号密码错误,还有%s机会"%(sum_c ))
        username = input("请输入账号:")
        passwd = input("请输入密码:")

username = input("请输入账号:")
passwd = input("请输入密码:")
count=1
sum_c=3
login_success=auth(username,passwd,count,sum_c)
if login_success == 1:
    print("登录成功")
else:
    print("登录失败")
print(auth)

#函数 不带参数
def foo():
    print("我就是随便发发文字而已")
foo()
有参与无参
#空函数
def
foo(): pass

2、函数:存在相同的函数名称出现的问题

#测试1-存在相同的函数名称
def foo():
    print("我就是随便发发文字而已")

def foo():
    print("吖啊啊,我是另外一个相同的函数名称")

foo()  #执行结果  吖啊啊,我是另外一个相同的函数名称

#测试2-相同的函数名称,一个带参,一个不带参数
def foo(x):
    x += 1
    print("我就是随便发发文字而已")

def foo():
    print("吖啊啊,我是另外一个相同的函数名称")

x=1
foo(x) # 报错,因为第二个函数并没有带参数 TypeError: foo() takes 0 positional arguments but 1 was given

 3、函数使用原则:先定义,后调用

#测试1  先调用函数  后定义
foo() #则会报错,NameError: name 'foo' is not defined

def foo():
    print("吖啊啊,我是另外一个相同的函数名称")

#测试2 调用函数 没有定义函数
def foo():
    print("吖啊啊,我是另外一个相同的函数名称")

foo()
foo1() #因为没有定义foo1()函数,则报错NameError: name 'foo1' is not defined

#测试3 多个函数调用
def foo():
    print("我是老大")
    foo1()
def foo1():
    print("我是老二")
foo() #先定义函数 后调用

#测试4 
# def foo():
#     print("我是老大")
#     foo1()
# foo()       #因为定义foo1() 是在调用foo()函数后面
# def foo1():
#     print("我是老二")
#则会报错 NameError: name 'foo1' is not defined

 

4、函数返回值

1、过程:就是没有返回值的函数
无return ->None
2、return 1个值-》返回一个值
3、return 逗号分割多个值-》元祖
#无return
def
test01(): print("吖啊啊,我是另外一个相同的函数名称")
#return 1个值
def test02(): x=1 return x
#return 多个值
def test03(): x=1 return x,1,2,3,(1,2),[1,2,'a'] test_01=test01() test_02=test02() test_03=test03() print(test_01) print(test_02) print(test_03) """ 执行结果 None 1 (1, 1, 2, 3, (1, 2), [1, 2, 'a']) """

5、函数的参数

形参即变量名,实参即变量值,函数调用时,将值传到变量名上,函数调用结束,

测试1-位置参数,必须从左到右顺序一一对应

#
实参与形参一一对应 def calc(x,y): res=x**y return res
c=calc(2,3) print(c) #实参缺失 c=calc(2) #实参缺失一个 报错TypeError: calc() missing 1 required positional argument: 'y' #实参多个 c=calc(2,2,3)#实参比形参多,报错TypeError: calc() takes 2 positional arguments but 3 were given
测试2-关键字参数,根据key=value的形式定义实参;无需一一对应,缺一不可;对同一个形参不能重复传值

#实参与形参无一一对应
def calc(x,y):
    res=x**y
    return  res

c=calc(y=2,x=1)
print(c) #可以正常输出
c=calc(y=2) #报错 TypeError: calc() missing 1 required positional argument: 'x'
c=calc(y=2,x=1,z=0) #报错TypeError: calc() got an unexpected keyword argument 'z'
测试3-位置参数和关键字参数一起混合使用,位置参数必须在关键字左边

def test(x,y,z):
    print(x,y,z)

#test(1,2,x=4) #TypeError: test() got multiple values for argument 'x'  因为位置参数1 已经传参给x 了;所以再重新赋值就会报错
#test(1,y=2,3) #报错 SyntaxError: positional argument follows keyword argument
test(1,2,z=3)  #正常输出 1 2 3
test(1,y=2,z=3) #正常输出 1 2 3
#test(1,2,z=3,y=1) #TypeError: test() got multiple values for argument 'y' 因为位置参数2 已经传参给y 了;所以再重新赋值就会报错
测试4-默认参数 形参在定义时就已经为其赋值
def test(x,y=2,z=3): print(x,y,z) test(1) #可正常输出1,2,3 ; 1传参给x ,y、z有默认值 test(1,4) #根据位置参数一一对应关系,则输出的是1,4,3 test(y='a',z='b',x='c') #则输出 c a b
测试5-可变长参数
        1、**字典
        2、*列表
-----------------*列表-----------------------------------
#实参 2,'a','b',{"a":1},True
def test(x,*args):
    print(x,args)   #输出1 (2,'a', 'b', {'a': 1}, True)
    print(args[0])  #输出 2

test(1,2,'a','b',{"a":1},True)

#实参 ['c','a','b',{"a":1},True]
def test(x,*args):
    print(x,args)   #输出1 (['c', 'a', 'b', {'a': 1}, True],)  列表中就一个元素
    print(args[0])  #输出 ['c', 'a', 'b', {'a': 1}, True]
    print(args[0][0])  #输出c

test(1,['c','a','b',{"a":1},True])

#实参 *['c','a','b',{"a":1},True]
def test(x,*args):
    print(x,args)   #输出 1 ('c', 'a', 'b', {'a': 1}, True)
    print(args[0])  #输出 c

test(1,*['c','a','b',{"a":1},True])

#参数不传给*args
def test(x,*args):
    print(x,args)   #输出 1 ()

test(1)

 

#-----------------**字典-----------------------------------
#实参 x=1,y=2,z=3,d='aa'
def test(x,**args):
    print(x,args)   #1 {'y': 2, 'z': 3, 'd': 'aa'}

test(x=1,y=2,z=3,d='aa')
#实参**{'b=2':2}
test(1,**{'b=2':2})  #1 {'b=2': 2}
#实参*{'b=2':2}
#test(1,*{'b=2':2})#报错 TypeError: test() takes 1 positional argument but 2 were given
#实参{'b=2':2}
#test(1,{'b=2':2})#报错 TypeError: test() takes 1 positional argument but 2 were given
#test(x=1,**{'x':1,'aa':2}) #报错 TypeError: test() got multiple values for keyword argument 'x'
#实参 **{'z':1,'y':2,'x':3}  形参 x,y,z
def test(x,y,z):
    print(x,y,z)
test(**{'z':1,'y':2,'x':3})  #输出的是3 2 1


def test(x,*args,**args1):
    print(x,args,args1)

test(1,2,3,4,5,6,7,8,1,name='d',d='aa')#1 (2, 3, 4, 5, 6, 7, 8, 1) {'name': 'd', 'd': 'aa'}
#test(1,*['a','b','c'],**{'yuyu':1,3:'x'})#报错TypeError: test() keywords must be strings
test(1,*['a','b','c'],**{'yuyu':1,'xxx':'x'}) #1 ('a', 'b', 'c') {'yuyu': 1, 'xxx': 'x'}
-----------无参数------------
def test(*args,**args1):
    print(args,args1)

test()  #输出结果() {}
test(2) #输出结果 (2,) {}
test('alex',18,'malx','x',yy=34) #输出结果('alex', 18, 'malx', 'x') {'yy': 34}

 

 

posted @ 2019-10-15 14:01  槑槑DE  阅读(317)  评论(0编辑  收藏  举报