Python学习-函数

本文详细介绍了Python中的函数概念,包括函数的创建与调用、参数的种类(位置参数、关键字参数、默认参数),返回值的处理,以及如何使用位置解包、关键字解包和函数的文档帮助。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

十九、函数

1、创建和调用函数
#函数的定义,pass在日常的编程中用来占坑位

>>> def myfunc():
pass

#函数的调用

>>> myfunc()
 
>>> def myfunc():
for i in range(3):
print("I love you.")
 
 
>>> myfunc()
I love you.
I love you.
I love you.

2、函数的参数:通过函数的参数来实现功能的定制
#可定义其中的参数来修改变量

>>> def myfunc(name):
for i in range(3):
print(f"I love {name}.")
 
 
>>> myfunc("Python")
I love Python.
I love Python.
I love Python.

#可定义多个参数

>>> def myfunc(name,times):
for i in range(times):
print(f"I love {name}.")
 
 
>>> myfunc("Python",5)
I love Python.
I love Python.
I love Python.
I love Python.
I love Python.

3、参数的调用的角度分类:形式参数、实际参数
1)形式参数(形参):是函数定义的时候写的参数的名字,比如上面例子中的name、times
2)实际参数(实参):是在调用函数的时候传递进去的值,比如上面例子中的Python、5

4、函数的返回值-return:

>>> def div(x,y):
z=x/y
return z
 
>>> div(4,2)
2.0

#或者可以这么写

>>> def div(x,y):
return x/y
 
>>> div(4,2)
2.0

#除数不能为0,完善代码

>>> def div(x,y):
if y == 0:
return "除数不能为0!"
else:
return x/y
 
 
>>> div(4,2)
2.0
>>> div(4,0)
'除数不能为0!'

#只要执行了return语句,函数就会立刻马上直接的返回,不会理会后面是否还有其他语句

>>> def div(x,y):
if y == 0:
return "除数不能为0!"
return x/y
 
>>> div(4,2)
2.0
>>> div(4,0)
'除数不能为0!'

#如果一个函数我们没有通过return语句显示的来返回内容,那么它也会自己在执行完函数体中的所有语句之后,悄悄的返回一个none值。

>>> def myfunc():
pass
 
>>> print(myfunc())
None

5、函数的参数
1)位置参数:Python中位置固定的参数,调用时需要按参数的顺序输入

>>> def myfunc(s,vt,o):
return "".join((o,vt,s))
 
>>> myfunc("我","打了","小甲鱼")
'小甲鱼打了我'

2)关键字参数:

>>> myfunc(o="我",vt="打了",s="小甲鱼")
'我打了小甲鱼'

3)同时使用位置参数和关键字参数,需要注意顺序:位置参数必须在关键字参数之前

>>> myfunc("小甲鱼","打了",o="我")
'我打了小甲鱼'

4)默认参数:允许函数的参数在定义的时候就指定默认值,在函数调用时,如果没有传入实参,那么就将采用默认的参数值来代替,如果我们使用默认参数,就应该把他们摆在最后。

>>> def myfunc(s,vt,o="小甲鱼"):
return "".join((o,vt,s))
 
>>> myfunc("香蕉","吃")
'小甲鱼吃香蕉'
>>> myfunc("香蕉","吃","不二如是")
'不二如是吃香蕉'

5)help函数查看这个函数文档时,会在函数的原型中看到一个/,表示斜杠左侧的参数,它必须传递位置参数,而不能是关键字参数。
#abs是求绝对值的函数

>>> help(abs)
Help on built-in function abs in module builtins:
 
abs(x, /)
    Return the absolute value of the argument.
 
>>> abs(-1.5)
1.5
>>> abs(x=-1.5)
Traceback (most recent call last):
  File "<pyshell#51>", line 1, in <module>
    abs(x=-1.5)
TypeError: abs() takes no keyword arguments

#sum是求和函数

>>> help(sum)
Help on built-in function sum in module builtins:
 
sum(iterable, /, start=0)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers
    
    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.
 
>>> sum([1,2,3],4)
10
>>> sum([1,2,3],start=4)
10
 

#自己定义的函数也遵循这个规则

>>> def abc(a,/,b,c):
print(a,b,c)
 
 
>>> abc(1,2,3)
1 2 3
>>> abc(a=1,2,3)
SyntaxError: positional argument follows keyword argument
>>> abc(1,b=2,c=3)
1 2 3

#限制只能使用关键字参数的语法:利用星号,星号表示左侧既可以是位置参数,也可以是关键字参数;但是右侧的只能是关键字参数才不会报错。

>>> def abc(a,*,b,c):
print(a,b,c)
 
 
>>> abc(1,2,3)
Traceback (most recent call last):
  File "<pyshell#63>", line 1, in <module>
    abc(1,2,3)
TypeError: abc() takes 1 positional argument but 3 were given
>>> abc(1,b=2,c=3)
1 2 3
>>> abc(a=1,b=2,c=3)
1 2 3

6)收集参数:函数并不知道会传入多少个参数,定义收集参数只需要在形参的名字前面,加上一个星号来表示就可以了。实际上是利用了元祖的打包和解包的功能。如果在收集参数后面还需要指定其他参数,那么在调用函数的时候,就应该使用关键字参数来指定后面的参数。否则Python就会把实参纳入到收集参数中。

>>> def myfunc(*args):
print("有{}个参数。".format(len(args)))
print("第2个参数是:{}".format(args[1]))
 
 
>>> myfunc("小甲鱼","爱吃鱼")2个参数。
第2个参数是:爱吃鱼
 
>>> def myfunc(*args,a,b):
print(args,a,b)
 
>>> myfunc(1,2,3,a=4,b=5)
(1, 2, 3) 4 5
 

#将参数打包为字典:使用2个连续星号。

>>> def myfunc(**kwargs):
print(kwargs)
 
 
>>> myfunc(a=1,b=2,c=3)
{'a': 1, 'b': 2, 'c': 3}
 

#混合使用

>>> def myfunc(a,*b,**c):
print(a,b,c)
 
>>> myfunc(1,2,3,5,x=5,y=6)
1 (2, 3, 5) {'x': 5, 'y': 6}

#format函数是包含2种收集参数的函数

>>> help(str.format)
Help on method_descriptor:
 
format(...)
    S.format(*args, **kwargs) -> str
    
    Return a formatted version of S, using substitutions from args and kwargs.
    The substitutions are identified by braces ('{' and '}').

7)解包参数:在传递参数的时候可以使用*对参数进行解包,**对应的是关键字参数。

>>> args=(1,2,3,4)
>>> def myfunc(a,b,c,d):
print(a,b,c,d)
 
 
>>> myfunc(args)
Traceback (most recent call last):
  File "<pyshell#93>", line 1, in <module>
    myfunc(args)
TypeError: myfunc() missing 3 required positional arguments: 'b', 'c', and 'd'
>>> myfunc(*args)
1 2 3 4

#**是将字典给解包成关键字参数

>>> myfunc(*args)
1 2 3 4
>>> kwargs={'a':1,'b':2,'c':3,'d':4}
>>> myfunc(**kwargs)
1 2 3 4
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值