1.1
定义函数:
def greet_user():
print (‘Hello the world‘)
执行函数: greet_user()
向函数传递参数:
def greet_user(username):
print (‘Hello,‘ + username.title() + ‘!‘ ) .title() 首字母大写
greet_user(‘lucy‘) 执行时括号里添加参数
def describe_pet(animal_type,pet_name):
‘‘‘显示宠物的信息‘‘‘
print("\nI have a " + animal_type + ‘.‘)
print("My " + animal_type + " name is " + pet_name.title() + ‘.‘)
describe_pet(‘hamster‘,‘harry‘)
describe_pet(‘dog‘,‘while‘) 调用先后顺序不能错
def describe_pet(animal_type,pet_name):
print(‘\n I have a ‘ + animal_type + ‘.‘)
describe_pet(animal_type=‘hamster‘,pet_name=‘dog‘) 关键字实参
1.2 默认值
编写函数时,可给每个形参制定默认值。调用函数时,给形参提供实参时,python将使用指定的实参,否则,将使用形参的默认值。
def greet_user(username=‘lucy‘):
print (‘hello‘)
greet_user()
2.1返回值
def get_formatted_name(first_name,last_name):
full_name = first_name + ‘ ‘ + last_name
return full_name.title() return将full_name 的值返回给函数get_formatted_name
musician = get_formatted_name(‘zn‘,‘zjy‘)
print(musician)
2.2 让实参变成可选的
def get_formatted_name(first_name,last_name,middle_name=‘‘):
if middle_name:
full_name = first_name + ‘ ‘ + middle_name + ‘ ‘ + last_name
else:
full_name = first_name + ‘ ‘ + last_name
return full_name.title()
musician = get_formatted_name(‘zn‘,‘zzz‘)
print(musician)
musician = get_formatted_name(‘zn‘,‘zzx‘,‘zjy‘)
print(musician)
3.1返回字典
函数可返回任何类型的值,包括列表和字典等比较复杂的数据结构
def build_person(first_name,last_name):
person = {‘first‘:first_name,‘last‘:last_name}
return person
musician = build_person(‘zn‘,‘zzx‘)
print(musician)
def build_person(first_name,last_name,age):
person = {‘first‘:first_name,‘last‘:last_name}
if age:
person[‘age‘] = age
return person
mulition = build_person(‘zn‘,‘zzx‘,‘29‘)
print(mulition)
结合使用函数和while循环:
def get_formatted_name(first_name,last_name):
full_name = first_name + ‘ ‘ + last_name
return full_name.title()
while True:
print(‘\nPlease tell your name:‘)
print("enter ‘q‘ at any time to quit")
f_name = input(‘first name:‘)
if f_name ==‘q‘:
break
l_name = input(‘last name:‘)
if l_name == ‘q‘:
break
formatted_name = get_formatted_name(f_name,l_name)
print(‘\nHello,‘ + formatted_name + ‘!‘)
传递任意数量的实参:
def make_pizza(*toppings):
print(toppings)
make_pizza(‘pepperoni‘)
make_pizza(‘zxc‘,‘dsa‘,‘das‘) 函数只有一个形参*topping,不管提供多少个实参,这个形参豆浆它们统统收入囊中
形参名*topping中的星号让python创建一个名为topping的空元祖,并将值封装到这个元祖中
def make_pizza(*toppings):
print(‘\nMaking a pizza with the following toppings:‘)
for topping in toppings:
print ("-" + topping)
make_pizza(‘pep‘)
make_pizza(‘5‘,‘4‘,‘3‘,‘2‘,‘1‘)