Python函数基本用法

来源:互联网 发布:mac响声很大 编辑:程序博客网 时间:2024/05/16 02:07
#author Fimport time#面向对象   : 类 --->class#面向过程   : 过程-->def#函数式编程 : 函数-->def#定义函数def func1():    """testing"""    print("in the func1")    return 0#定义过程def func2():    """testing"""    print("in the func2")x=func1()  #in the func1y=func2()  #in the func2print("result from func1 %s" % x)  #result from func1 0print("result from func2 %s" % y)  #result from func2 None #无return 隐式返回一个nonedef function():    time_format = "%Y-%m-%d %X"    time_current = time.strftime(time_format)    print("hahahaha %s" %time_current)function()function()function()#返回值def function1():    print("function1")def function2():    print("function2")    return 0def function3():    print("function3")    return 1, "string", ["list1", "list2"], {"name":"Aha"} #以元祖的形式返回x = function1()y = function2()z = function3()print(x)    #返回数= 0 (未返回)  ->返回noneprint(y)    #返回数= 1 (返回1个值)  ->返回objectprint(z)    #返回数= 多个 ->返回元组#有参函数 形参def add(x,y): #形参 位置参数    print(x)    print(y)# add(1, 2)  #位置参数调用 与形参一一对应# add(y=2, x=1)  #关键字调用 与形参顺序无关##关键参数是不能写在位置参数前面的 关键字参数一定要在位置参数后面 位置参数在关键字参数前面# add(2, x=3)  #既不是位置调用 也不是关键字调用 无法运行 2给x,3又通过关键字调用给了xadd(3, y=2)##默认参数特点:调用函数时 默认参数非必须传递(相当于默认安装值)def test(x, y=2):    print(x)    print(y)##参数组def test_arr(*args):  #接受多个实参  (N个__位置参数__ 转换成元组的形式  不接受关键字参数)    print(args)test_arr(1, 2, 3, 4, 5, 6)  #参数组传参方式test_arr(*[1, 3, 3, 5, 5])  #参数组args = turple([1,3,3,5,5])def test_combine(x, *args):    print(x)    print(args)test_combine(1,2,3,45,5)def test_diction(**kwargs): #接受字典  (N个__关键字__参数转为字典)    print(kwargs)    print(kwargs['name'])test_diction(name='HHH', age="2", sex="F") #{'name': 'HHH', 'age': '2', 'sex': 'F'}test_diction(**{'name':'HHH', 'age':"2", 'sex':"F"}) #{'name': 'HHH', 'age': '2', 'sex': 'F'}def test_diction_combine(name, **kwargs):    print(name)    print(kwargs)# test_diction_combine("axiba", "ss") #报错 ss是字符串 要用关键字方式传递test_diction_combine("axiba", sex="male", hobby="drink")def test_diction_args(name, age=18, **kwargs):    print(name)    print(age)    print(kwargs)test_diction_args("aaa", sex="m", hobby="sing")test_diction_args("aaa", age="111", sex="m", hobby="sing")

原创粉丝点击