Python中的函数

目录

一、基本用法

二、函数返回值

三、传递任意参数


 

一、基本用法

  • 定义函数
  • 声明参数
  • 参数默认值

# 定义函数
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)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值