目录
一、基本用法
- 定义函数
- 声明参数
- 参数默认值
# 定义函数
def hello():
print("hello world.")
hello()
print("-----------------------")
# 声明参数
def hello2(name):
print("hello,", name)
hello2("lijiang")
print("-----------------------")
# 参数默认值
def hello3(name="lijiang"):
print("哈喽,", name)
hello3()
hello3("张三")
二、函数返回值
- 返回数值
- 返回字符
- 返回字典
# 返回数值
def add(x, y):
return x + y
print(add(10, 20))
print("-------------------")
# 返回字符
def user(username, password):
str = ""
str += "username=" + username + ";"
str += "password=" + password + ";"
return str
print(user("lijiang", "123"))
print("-------------------")
# 返回字典
def user(username, password):
return {
"username": username,
"password": password,
}
db = user("lijiang", 123)
print(db)
print(db["username"])
print(db["password"])
三、传递任意参数
- 传递任意参数
- 传递关键字参数
# 传递任意参数
def add(*num):
result = 0
for val in num:
result += val
return result
print(add(1, 2, 3))
print(add(1, 2, 3, 4, 5))
print("-----------------")
# 传递关键字参数
def sendmail(**data):
for key, val in data.items():
print(key, ":", val)
sendmail(username="lijiang", password=123)