1. 示例
def greet_user(): # 函数定义
"""显示简单的问候语""" # 文档字符串,描述了函数的功能。Python基于此生成有关函数的文档
print("Hello!")
greet_user()
1.1 参数
def greet_user(username):
"""显示简单的问候语"""
print(f"Hello, {username.title()}")
greet_user("jesse")
username是形参,"jesse"是实参
2. 传递实参的方式
当函数有多个形参时,函数调用时也会包含多个实参。形参和实参的关联方式有以下方式
2.1 位置实参
实参的顺序与形参顺序一致
def describe_pet(animal_type, pet_name):
"""显示宠物的信息。"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')
2.2 关键字实参
无需考虑实参顺序
def describe_pet(animal_type, pet_name):
"""显示宠物的信息。"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(animal_type = 'hamster', pet_name = 'harry')
describe_pet(pet_name = 'willie', animal_type = 'dog')
2.3 形参指定默认值
函数定义使用默认值时,必须先列出无默认值的形参,再列出有默认值的形参。
def describe_pet(pet_name, animal_type='dog'):
"""显示宠物的信息。"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet('xiaohuang') # 按形参顺序
describe_pet(pet_name = 'willie') # 按参数名
describe_pet(animal_type = 'hamster', pet_name = 'harry') # 显式指定pet_name, 将忽略默认值
3. 返回值
3.1 示例
def get_formatted_name(first_name, last_name):
"""返回整洁的姓名。"""
full_name = f"{first_name} {last_name}"
return full_name.title()
actor = get_formatted_name('tom', 'hanks')
print(actor)
让实参可选
def get_formatted_name(first_name, last_name, middle_name=''):
""""返回整洁的姓名。"""
if middle_name: # middle_name非空,则为True
full_name = f"{first_name} {middle_name} {last_name}"
else:
full_name = f"{first_name} {last_name}"
return full_name
actor = get_formatted_name('jim', 'hendrix')
print(actor)
actor = get_formatted_name('john', 'hooker', 'lee')
print(actor)
3.2 返回字典
def build_person(first_name, last_name, age=None): # age设置为可选,None表示变量没有值,占位符
person = {'first': first_name, 'last':last_name}
if age:
person['age'] = age
return person
actor = build_person('tom', 'hanks', age=33)
print(actor)
标签:函数,python,describe,pet,animal,print,type,name
From: https://www.cnblogs.com/route/p/17538029.html