python ---- 函数

本文详细介绍了Python中的函数定义、调用,包括如何传递参数(位置参数、默认值、关键字参数),以及返回值和可选参数的使用。还展示了如何创建和使用字典作为函数返回结果。
摘要由CSDN通过智能技术生成

 / 定义函数

def 函数名:

        函数体

函数调用

def hanshu():       #定义函数
     print('Hello World !')
     print('Hello World !')
hanshu()

 /  向函数传递信息

def hanshu(name): #name是形参
     print(f'Hello {name} !')
hanshu('joker')  #joker是实参

   / 传递实参

1.

def hanshu(name,age):
     print(f'Hello {name} !')
     print(f'You are {age} now.')
hanshu('joker','18')

2.默认值

def hanshu(name,age = "18"):
     print(f'Hello {name} !')
     print(f'You are {age} now.')
hanshu('joker')

def hanshu(name,age = "18"):
     print(f'Hello {name} !')
     print(f'You are {age} now.')
hanshu('joker','20')

3.关键字

def hanshu(name,age = "18"):
     print(f'Hello {name} !')
     print(f'You are {age} now.')
hanshu(age = '20',name='joker')

此时,与实参的顺序无关

 / 返回值

def hanshu(name,age):
    information = f'the name is {name} \nthe age is {age}'
    return information #返回
infor = hanshu("joker","18")
print(infor)

  /  实参可选

def hanshu(name,age,others=''):
    if others:
        information =f'{name} {age} {others}'
    else:
        information= f'{name} {age}'
    return information  #返回值
infor = hanshu("joker","18",'1774585')
print(infor)
infor = hanshu("joker","18")
print(infor)

  / 返回一个字典

def dictionary(green,two,ten = None):
        person={'color': green,
        'height':two}
        if ten:
            person['ten']=ten
        return dictionary
dic = {'red','ten','two'}
print(dic)

  / 使用 as  命名

 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值