Python函数基本用法

#author F
import time
#面向对象   : 类 --->class
#面向过程   : 过程-->def
#函数式编程 : 函数-->def

#定义函数
def func1():
    """testing"""
    print("in the func1")
    return 0
#定义过程
def func2():
    """testing"""
    print("in the func2")

x=func1()  #in the func1
y=func2()  #in the func2

print("result from func1 %s" % x)  #result from func1 0
print("result from func2 %s" % y)  #result from func2 None #无return 隐式返回一个none


def 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 0

def function3():
    print("function3")
    return 1, "string", ["list1", "list2"], {"name":"Aha"} #以元祖的形式返回

x = function1()
y = function2()
z = function3()
print(x)    #返回数= 0 (未返回)  ->返回none
print(y)    #返回数= 1 (返回1个值)  ->返回object
print(z)    #返回数= 多个 ->返回元组

#有参函数 形参

def add(x,y): #形参 位置参数
    print(x)
    print(y)

# add(1, 2)  #位置参数调用 与形参一一对应
# add(y=2, x=1)  #关键字调用 与形参顺序无关
##关键参数是不能写在位置参数前面的 关键字参数一定要在位置参数后面 位置参数在关键字参数前面
# add(2, x=3)  #既不是位置调用 也不是关键字调用 无法运行 2给x,3又通过关键字调用给了x
add(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")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值