关键字实参
1.关键字实参事传递给函数的名称——值对。无需考虑函数调用实参顺序,而且清楚地指出了函数调用中各个值的用途。
def describe_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='harry', animal_type='hamster')
输出为
I have ahamster,
My hamster's name is Harry.
I have ahamster,
My hamster's name is Harry.
默认值
编写函数时,可给每个形参指定默认值,在调用函数中给形参提供了实参时,Python将使用指定的实参值;否则,将使用形参的默认值
注意:把含有默认值的参数放在了不含默认值的参数的前面会报错
def describe_pet(animal_type = 'dog' , pet_name):
print("\nI have a" + animal_type + ",")
print("My "+ animal_type +"'s name is " + pet_name.title() + '.')
File "E:/python project document/python编程快速上手1.py", line 1
def describe_pet(animal_type = 'dog' , pet_name):
^
SyntaxError: non-default argument follows default argument
将animal_type默认值设置为'dog'。调用函数时如果没有给animal_type指定指,Python将把这个形参设置为'dog'。如果调用的时候只包含一个实参,将关联到函数定义中的第一个形参。这也是为什么要将没有默认值的参数放在形参列表的开头。现在,可以在函数调用中只提供小狗的名字:
def describe_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='miaoge')
describe_pet('miaoge')
describe_pet(pet_name= 'hurry',animal_type='hamster')
I have adog,
My dog's name is Miaoge.
I have adog,
My dog's name is Miaoge.
I have ahamster,
My hamster's name is Hurry.
Python将非空字符串解读为True,因此可以给实参指定默认值——空字符串,让实参变成可选的
def function(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()
传递任意数量的实参
def make_pizza(*toppings)
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
topping中的让Python创建一个名为toppings的控元组,并将收到的所有值都装到这个元组中
模块
1.导入整个模块
将函数储存在被称为模块的独立文件中,再将模块导入到主程序中,import语句允许在当前运行的程序文件中使用模块中的代码。
先创建一个包含函数make_pizza()的模块,为此,将文件pizza.py中除函数make_pizza()之外的其他代码都删除
pizza.py
def make_pizza(size,*toopings):
print('\nmaking a ' + str(size)+ '-inch pizza with the following topping:s')
for tooping in toopings:
print('-'+ tooping)
接下来在 pizza.py所在目录中创建另一个名为making_pizza.py的文件,这个文件导入刚创建的模块,再调用make_pizza()
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12,'mushroons','green peppers','extra cheese')
输出
making a 16-inch pizza with the following topping:s
-pepperoni
making a 12-inch pizza with the following topping:s
-mushroons
-green peppers
-extra cheese