本文主要是梳理下Python函数的传参机制,主要内容包含:

一、最简单的函数(无返回值、参数)
def hello_python():
print("hello python!")
hello_python() # 直接调用
hello python!
二、最简单的函数(带返回值、无参数)
def hello_python():
data = "hello python!"
return data # data就是返回值
hello_python()
'hello python!'
三、带一个参数(无默认值)
def hello(data):
result = "hello " + data
return result
hello("python")
'hello python'
传入另一个值:
hello("java")
'hello java'
还可以在内部修改参数的信息:
def hello_name(name):
result = "Hello " + name.title() + "!"
return result
hello_name("tom")
'Hello Tom!'
hello_name("jack")
'Hello Jack!'
四、带有多个参数(无默认值)
def information(name, age):
data = "我叫" + name.title() + ", 今年" + str(age) + "岁"
return data
information("tom", 23)
'我叫Tom, 今年23岁'
information("JACK", 18)
'我叫Jack, 今年18岁'
五、参数设置默认值(一个参数)
def hello_name(name="Peter"):
result = "Hello " + name
return result
如果不给参数具体的值,就使用默认值
hello_name()
'Hello Pete

本文详细介绍了Python函数的各种传参方式,包括无参数、有返回值、带默认值参数、多个参数、位置实参、关键字实参、*args和**kwargs的使用,以及它们的组合使用情况,帮助读者深入理解Python函数参数的传递机制。
最低0.47元/天 解锁文章
4260





