Python函数

- 一、怎么定义:
函数的定义关键字def
def 函数名():
内容

def fuction1():
    print("内容")
fuction1()
#结果:内容

-二、 传参类型:

  1. 传一个参数
def fuction1(x):
    print(x)
fuction1(3)
#结果:3
  1. 传两个参数
def fuction1(x,y):
    print(x,y)
fuction1(3,4)#结果:fuction1(3,4)
fuction1(y=3,x = 4)#关键字调用,结果:4 3
fuction1(3,y = 4)#结果:3 4,多个参数传值时,未知参数在前。
  1. 传n参数
    使用这种方式传参,你如果想加点未知参数,那就只能放在后面
    def fuction1(x,*dictionary)
def fuction1(*dictionary):
    print(dictionary)
#无论我给他传多少个值,他都会将他以元组的方式打印出来。
fuction1(3,4,5,6,6)
#结果:(3, 4, 5, 6, 6)
fuction1(*[1,2,3,4])
#结果:(1,2,3,4)
  1. 传字典
    传字典类型,是两个*
def fuction1(**dictionary):
    print(dictionary)
fuction1(age = 1,name = "Dongdong")
#结果:{'age': 1, 'name': 'Dongdong'}
  1. 传一个函数
    这里我把f当做函数
def fuction1(x,f):
    print(f(x))
#这里的abs我们传的是自带的绝对值函数
fuction1(-1,abs)
#结果:1

-三、 Return一下:
return就是返回值类型,他帮助返回一个你想要的数据。比如说你有一个非零实数,
你想判断是正数还是负数。

def fuction1(x):
    if x>0:
        return "正数"
    else:
        return "负数"
print(fuction1(3))
#结果:正数

-四、 温馨提示:
函数里面不要使用global定义全局变量,不万不得已也不要在里面修改全局变量,因为一个函数
可能会被使用很多次,到时候全局变量在哪被修改了,你都很懵逼。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值