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'}