传递实参
- 按位置传递参数
def describe_pet(animal_type,pet_name):
print("I have a "+animal_type+".")
print("My "+animal_type+"'s name is "+pet_name.title()+".")
describe_pet('dog','heii')
输出结果
I have a dog.
My dog's name is Heii.
- 关键字传递
describe_pet(pet_name='heii',animal_type='dog')
输出结果
I have a dog.
My dog's name is Heii.
- 给形参指定一个默认值
def describe_pet(pet_name,animal_type='dog'):
print("I have a "+animal_type+".")
print("My "+animal_type+"'s name is "+pet_name.title()+".")
describe_pet('heii')
describe_pet(pet_name='heii')
输出结果
I have a dog.
My dog's name is Heii.
I have a dog.
My dog's name is Heii.
返回值
- 返回一句话
def describe_pet(pet_name,animal_type='dog'):
pet="My "+animal_type+"'s name is "+pet_name.title()+"."
return pet
des=describe_pet('heii')
print(des)
输出结果
My dog's name is Heii.
- 返回字典
def describe_pet(pet_name,animal_type='dog'):
pet={'animal_type':animal_type,'pet_name':pet_name}
return pet
des=describe_pet('heii')
print(des)
输出结果
{'animal_type': 'dog', 'pet_name': 'heii'}
- 传递列表
def c(number):
for num in number:
print(num.title())
number=['one','two','three','four']
c(number)
输出结果
One
Two
Three
Four
- 修改列表
若不想让列表被修改,可以传递列表副本,列表切片 - 传递任意数量的实参
def c(*number):
print(number)
c('one','two','three','four')
c('one')
输出结果
('one', 'two', 'three', 'four')
('one',)