一、定义函数
定义一个简单的函数
def greet_user():
print("Hello!")
greet_user()
#执行结果:Hello!
二、参数传递
1)位置实参
传递参数的方式与实参的位置相关
def greet_user(words,name):
print(f"{words},{name}")
greet_user("Hello","John")
#执行结果:Hello,John
2)关键字实参
传递参数的方式与实参中使用的关键字相关
def greet_user(words,name):
print(f"{words},{name}")
greet_user(name="John",words="Hello")
#执行结果:Hello,John
【注意】
- 使用关键字实参时要注意正确输入形参的名字
- 使用关键字实参可以不分顺序地传入参数
3)默认值
def greet_user(words,name='John'):
print(f"{words},{name}")
greet_user("Hello")
#执行结果:Hello,John
【注意】
- 带有默认值的形参一定要在其他没有默认值参数的后面
三、传递列表
传递列表时,一定要注意在实参中传入的时列表的副本还是原列表
1)允许函数修改原列表
words=['a','b','c','d','e']
def decrease_words(words):
words.pop()
print(words)
""""传入了原列表"""
decrease_words(words)
print(words)
#执行结果:
#['a', 'b', 'c', 'd']
#['a', 'b', 'c', 'd']
2)不允许函数修改原列表
words=['a','b','c','d','e']
def decrease_words(words):
words.pop()
print(words)
""""传入了列表副本"""
decrease_words(words[:])
print(words)
#执行结果:
#['a', 'b', 'c', 'd']
#['a', 'b', 'c', 'd', 'e']
四、传递任意数量实参
传入的任意数量实参会以元组的形式传入,无法进行修改。
通常会以*args作为形参。
def greet_user(name,*words):
print(f"{name},{words}")
greet_user("Lili","Hello","Hi","How are you")
#执行结果:Lili,('Hello', 'Hi', 'How are you')
五、传递任意数量的关键字实参
传入的任意数量关键字实参会以字典的方式传入
通常会以**kwargs作为形参。
def build_profile(first, last, **user_info):
user_info['first_name']=first
user_info['last_name']=last
return user_info
user_profile=build_profile('Li','ming',location='China',age=18)
print(user_profile)
#执行结果:{'location':'China','age':'18','first_name':'Li','last_name':'ming'}
六、模块
通常我们会把一些函数放到其他的文件中,这样的文件我们称为模块。
在主程序的文件中想使用其他模块中的函数,需要对模块进行导入。
myfunc.py:
def func(name,message):
print(f"{name}:{message}")
main.py:
"""1.导入整个模块,使用模块中的函数时需要使用xxx.xxx()"""
import myfunc
myfunc.func("Lili","Hello")
"""2.导入某个模块中的函数,可以直接使用函数名"""
from myfunc import func
func("Lili","Hello")
"""3.导入某个模块中的函数并且起了一个别名,可以使用函数的别名"""
from myfunc import func as fn
fn("Lili","Hello")
"""4.导入整个模块并且起了一个别名,可以利用别名使用函数"""
import myfunc as mf
mf.func("Lili","Hello")
"""5.导入某个模块中的所用东西,直接使用函数名"""
from myfunc import *
func("Lili","Hello")