#example 1
def great_user(name):
print(f"Hello, {name}")
great_user("wang")
def favorite_book(title):
print(f"My favorite bool is {title}")
favorite_book("Alice in Wonderland")
#example 2
def describe_pet(pet_type , pet_name):
print(f"I have a {pet_type}.")
print(f"\nMy {pet_type}'s name is {pet_name.title()}.")
describe_pet('hamster','harry')
describe_pet('dog','willie')
def describe_animal(animal_name,animal_type = 'dog'): #默认值要放在最后面,因为先赋值给前面的形参
print(f"\nI have a {animal_type}, its name is {animal_name.title()}")
#等效的函数调用
describe_animal("willie")
describe_animal(animal_name='willie')
describe_animal('harry','hamster')
describe_animal(animal_name='harry', animal_type='dog')
describe_animal(animal_type='dog', animal_name='little white')
#example3 简单返回值
def get_formatted_name(first_name, last_name):
full_name = f"{first_name} {last_name}"
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
#example 4
def get_formatted_name(first_name,last_name,middle_name=''):
if middle_name:
full_name = f"{first_name} {middle_name} {last_name}"
else:
full_name = f"{first_name} {last_name}"
return full_name
musician = get_formatted_name('jimi','hendrix')
print(musician)
musician = get_formatted_name('john','hooker','lee')
print(musician)
#example 5 返回字典
def build_person(first_name,last_name,age=None):
person = {'first':first_name, 'last':last_name}
if(age):
person['age'] = age
return person
musician = build_person('jimi','hendrix',age=27)
print(musician)
#传递列表
def greet_users(names):
for name in names:
msg = f"Hello, {name.title()}!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
#传递任意数量的实参
def make_pizza(*toppings):
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print(f" - {topping}")
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
#传递任意数量的实参
def make_pizza(size, *toppings):
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f" - {topping}")
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')
#使用任意数量的关键字实参
def build_profile(first, last, **user_info):
#函数的定义要求提供名和姓,同时允许根据需要提供任意数量的名称值对。形参**user_info中的两个星号让python创建一个名为user_info的空字典
#并所有的名称值对都放到这个字典中
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
user_profile = build_profile('albert', 'einstein', location = 'princeton', field = 'physics')
print(user_profile)