1定义函数并且调用 注释语句""" """
def greet_user():
"""显示简单的问候语"""
print("hello!") greet_user()
2定义带参数的函数
def greet_user(username):
"""显示简单的问候语"""
print("hello" + username.title() + "!") greet_user('baker')
3 形参和实参
def describe_pet(animal_type,pet_name):
"""显示宠物信息"""
print("\n I have a " + animal_type +".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".") describe_pet('hamster','harry')
describe_pet('dog','willie') describe_pet(pet_name='willie',animal_type='dog')
4 有返回值的函数
def get_formatted_name(first_name,last_name):
"""返回整洁的名字"""
full_name = first_name + " "+last_name
return full_name.title() musician = get_formatted_name("jimi" , "baker") print(musician)
5 参数可以为空的函数
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('jimi','hendrix')
print(musician)
6 返回值可以是字典 或者列表
def build_person(first_name,last_name):
"""返回一个字典,其中包含一个人的信息"""
person = {'first':first_name, 'last':last_name}
return person musician = build_person('jimi','hendrix')
print(musician)
7 返回是字典,有额外的信息
def build_person(first_name,last_name,age=''):
"""返回一个字典,其中包含一个人的信息"""
person = {'first':first_name, 'last':last_name}
if age:
person['age'] = age return person musician = build_person('jimi','hendrix',age=)
print(musician)
8 函数和while循环
def get_formatted_name(first_name,last_name):
"""返回整洁的名字"""
full_name = first_name + " " + last_name
return full_name.title() while True:
print("\n Please tell me your name")
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 + "!")