python 怎么用mad函数_python入门学习------函数

1.定义函数:

def greet():

print("hello")

greet()

1.2向函数传递信息

def user(name):

print("hi,"+name+".")

user("jack")

输出结果:

hi,jack.

2.实参和形参

关键字实参

def pet(animal,pet):            /*形参

print("\nI have a"+animal+".")

print(animal+"'s name is "+pet.title()+".")

pet(animal='dog',pet='doudou')              /*实参

输出结果:

I have adog.

dog's name is Doudou.

默认值

def pet(pet,animal='dog'):

print("\nI have a "+animal+".")

print(animal+"'s name is "+pet.title()+".")

pet(pet='doudou')

输出结果:

I have a dog.

dog's name is Doudou.

注意:在这种情况下如果我们又给了实参,那么不输出默认值。

返回值

有时,我们的函数并不总是输出形式,当我们通过函数得到一个值时,我们要把它作为返回值,例如:

def name(first_name,last_name):

full=first_name+" "+last_name

return full.title()

aa=name('du','xiaoxiao')

输出结果:

Du Xiaoxiao

实参变成可选的(当某个函数有时候不需要某个实参的时候)

def name(first_name,last_name,mid_name=''):

full=first_name+" "+mid_name+" "+last_name

return full.title()

aa=name('du','xiaoxiao')

print(aa)

bb=name('du','jin','du')

print(bb)

输出结果;

Du  Xiaoxiao

Du Du Jin

传递任意数量的实参

def make_pizza(*toppings):            /*通过这种方式,就可以调用任意数量的实参

print(toppings)

for topping in toppings:

print(topping)

make_pizza("shd","shfdhjh")

make_pizza("shdshd")

输出结果:

('shd', 'shfdhjh')

shd

shfdhjh

('shdshd',)

Shdshd

使用任意数量的关键字实参  (书的131页)

def name(first,last,**info):

aa={}

aa['first']=first

aa['last']=last

for key,value in info.items():

aa[key]=value

return aa

bb=name('qq','ee',thing_1='apple',thing_2='orange')

print(bb)

输出结果:

{'first': 'qq', 'last': 'ee', 'thing_1': 'apple', 'thing_2': 'orange'}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值