#传递实参#位置实参:基于实参的顺序关联形参defdescribe_pet(animal_type,pet_name):"""显示宠物的信息"""print("\nI have a "+animal_type+".")print("My "+animal_type+"’s name is "+pet_name.title()+".")
describe_pet("hamster","harry")#1 调用函数多次
describe_pet("dog","willie")
describe_pet("cat","hx")#2 位置实参的顺序很重要#关键字实参:在实参中将名称和值关联起来了defdescribe_pet(animal_type,pet_name):"""显示宠物的信息"""print("\nI have a "+animal_type+".")print("My "+animal_type+"’s name is "+pet_name.title()+".")
describe_pet(animal_type="hamster",pet_name="harry")
describe_pet(pet_name="yyy",animal_type="cat")#默认值defdescribe_pet(pet_name,animal_type="dog"):"""显示宠物的信息"""print("\nI have a "+animal_type+".")print("My "+animal_type+"’s name is "+pet_name.title()+".")
describe_pet(pet_name="harry")
describe_pet("harry")#等效的函数调用defdescribe_pet(pet_name,animal_type="dog"):print("\nI have a "+animal_type+".")print("My "+animal_type+"’s name is "+pet_name.title()+".")
describe_pet(pet_name="harry")
describe_pet("harry")
describe_pet("harry","hamster")
返回值
#返回值defget_formatted_name(first_name,last_name):"""返回整洁的姓名"""
full_name=first_name+" "+last_name
return full_name.title()
musician=get_formatted_name("jimi","hendrix")print(musician)#让实参变成可选的defget_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)
musician=get_formatted_name("john","hooker","lee")print(musician)#返回字典defbuild_person(first_name,last_name):"""返回一个字典,其中包含有关一个人的信息"""
person={"first":first_name,"last":last_name}return person
musician=build_person("Chen","Rong")print(musician)defbuild_person(first_name,last_name,age=""):"""返回一个字典,其中包含有关一个人的信息"""
person={"first":first_name,"last":last_name}if age:
person["age"]=age
return person
musician=build_person("Chen","Rong",age=27)print(musician)#结合使用函数和while循环defget_formatted_name(first_name,last_name):"""返回整洁的姓名"""
full_name=first_name+" "+last_name
return full_name.title()#这是一个无限循环whileTrue:print("\nPlease tell me 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+"!")