输入:
def greet_user():
print("Hello!")
输出:
greet_user()1.2 默认值
使用默认值可以在传参的时候,选择对这个部分不传递参数,如
输入:
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(pet_name='willie')
输出:
I have a dog. My dog's name is Willie.
若选择对这一部分进行传参,则会忽略这个形参的默认值
可以使用下面这样进行调用函数
describe_pet('willie')
describe_pet(pet_name='willie')
describe_pet('harry', 'hamster')
describe_pet(pet_name='harry', animal_type='hamster')
describe_pet(animal_type='hamster', pet_name='harry')
除了列表传递的实参,在函数调用后,在主函数内不会发生改变。
将直接将列表表传递给函数后(列表传递的参数相当于一个地址),函数就可对其进行修改,也可以选择不修改。如
输入:
def gaibian(list): list[0]='new' def bugaibian(list): list[0]='newnew' list=['old'] gaibian(list) print(list) bugaibian(list[:]) #list[:]相当于list的一个副本 print(list)
输出:
['new'] ['new']
1.3 返回值
一个普通的实例,
输入:
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)
输出:
{'first': 'jimi', 'last': 'hendrix', 'age': 27}
1.4 传递任意数量的实参
如,
输入:
def make_pizza(*toppings):
"""打印顾客点的所有配料。"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
输出:
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')
形参名*toppings 中的星号让Python创建一个名为toppings 的空元组,并将收到的所有值都封装到这个元组中。
如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。如
输入:
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')
输出:
Making a 16-inch pizza with the following toppings: - pepperoni Making a 12-inch pizza with the following toppings: - mushrooms - green peppers - extra cheese



