使用def关键字定义函数。
def 函数名():
def great_user(username):
print(f"{username.title()},hello!")
great_user("jessi")
实参和形参
调用函数时,将要让函数使用的信息放在圆括号内。在greet_user(‘jesse’) 中,将实参’jesse’ 传递给了函数greet_user() ,这个值被赋给了形参username。
调用函数时,Python必须将函数调用中的每个实参都关联到函数定义中的一个形参。为此,最简单的关联方式是基于实参的顺序。这种关联方式称为位置实参。
def describie_pet(animal_type,pet_name):
print(f"I have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}")
describie_pet('hamster','harry')
describie_pet('dog','willie')
使用位置实参来调用函数时,实参的顺序必须正确。
关键字实参是传递给函数的名称值对,此时无需关注顺序。
def describie_pet(animal_type,pet_name):
print(f"I have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}")
describie_pet(animal_type='hamster',pet_name='harry')
describie_pet(pet_name='willie',animal_type='dog')
编写函数时,可给每个形参指定默认值。
def describie_pet(animal_type,pet_name='winnie'):
print(f"I have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}")
describie_pet(animal_type='hamster',pet_name='harry')
describie_pet('dog')
def make_shirt(size,text):
print(f"The shirt's size is {size} and the text will be printed on it is {text.title()}")
def make_shirt_default(size='XL',text = 'I love Python'):
print(f"The shirt's size is {size} and the text will be printed on it is {text.title()}")
print('8-3')
make_shirt('M','make everyday counts')
make_shirt(size='L',text='time is money')
print('8-4')
make_shirt_default()
make_shirt_default(size='M')
make_shirt_default(text='I am the best')
在定义函数时使用return关键字返回函数结果,在使用函数时使用一个变量接收函数的返回结果。
def get_name(first_name,last_name):
full_name = f"{first_name} {last_name}"
return full_name.title()
musician = get_name('jimi','ma')
print(musician)
给形参一个默认的空值,然后再函数中使用条件语句,让当用户使用该形参和不适用该形参时函数都可以使用。
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.title()
musician = get_formatted_name('jimi','ma')
print(musician)
musician_1 = get_formatted_name('will','hooker','lee')
print(musician_1)
函数可以返回列表、字典等复杂数据类型。
def build_person(first_name,last_name,age=None):
person = {'first_name':first_name,'last_name':last_name}
if age:
person['age'] = age
return person
musician = build_person('jimi','hendrix',27)
print(musician)
None值用法:none值详解
def get_formatted_name(first_name, last_name):
full_name = f"{first_name} {last_name}"
return full_name.title()
while True:
print("\nPlease tell me your name")
print("(enter 'q' at any time to quit)")
f_name = input("First name: ")
if f_name == 'q':
break
l_name = input("Last name: ")
if l_name == 'q':
break
format_name = get_formatted_name(f_name,l_name)
print(f"Hello, {format_name}!")
def city_country(city,country):
return f"{city.title()},{country.title()}"
def make_album(name,singer,num_songs = None):
album = {'name':name,'singer':singer}
if num_songs:
album['number of songs'] = num_songs
return album
print('8-6')
print(city_country('zibo','china'))
print(city_country('florence','italy'))
print(city_country('madrid','spain'))
print('8-7')
print(make_album('love and peace','jack',5))
print(make_album('nature','diane'))
print('8-8')
while True:
print("Enter the singer and album's name(enter q to exit)")
singer = input("Enter the singer: ")
if singer == 'q':
break
name = input("Enter the album name: ")
if name == 'q':
break
album = make_album(name,singer)
print(f"The album's name is {album['name'].title()} and the singer is {album['singer'].title()}")
将列表作为参数在函数中进行传递。
def greet_users(names):
for name in names:
print(f"Hello,{name.title()}!")
username = ['hannah','will','grace']
greet_users(username)
在函数中完成列表的修改,并且专门定义一个函数完成列表元素的输出。
def print_models(unprinted_models, completed_models):
while unprinted_models:
current_design = unprinted_models.pop()
print(f"Printing model: {current_design}")
completed_models.append(current_design)
def show(completed_models):
print('The following models have been printed:')
for completed_model in completed_models:
print(completed_model)
unprinted_models = ['phone case','robot pendant','dodecahedron']
completed_models = []
print_models(unprinted_models,completed_models)
show(completed_models)
如果不想让函数修改列表中的内容,可以向函数中传递列表的副本,这样做可以只对列表副本进行修改,但是原列表内容不会受影响。
创建列表副本:
如何拷贝列表
def print_models(unprinted_models, completed_models):
while unprinted_models:
current_design = unprinted_models.pop()
print(f"Printing model: {current_design}")
completed_models.append(current_design)
def show(completed_models):
print('The following models have been printed:')
if completed_models==[]:
print("This list is empty")
else:
for completed_model in completed_models:
print(completed_model)
unprinted_models = ['phone case','robot pendant','dodecahedron']
completed_models = []
print_models(unprinted_models[:],completed_models)
show(unprinted_models)
show(completed_models)
可以看到由于使用了unprinted_models列表的副本,所以其元素没有被改变。
def show_message(text):
for t in text:
print(f"{t.title()}")
def send_message(text1,text2):
while text1:
t = text1.pop()
print(f"{t.title()}")
text2.append(t)
def print_list(list1):
if list1 == []:
print("This is an empty list.")
else:
for l in list1:
print(f"{l.title()}")
print('8-9')
text = ['hello','good morning','goodbye','thank you']
show_message(text)
print('8-10')
text1 = ['hello','good morning','goodbye','thank you']
text2=[]
send_message(text1,text2)
print_list(text1)
print_list(text2)
print('8-11')
text1 = ['hello','good morning','goodbye','thank you']
text2=[]
send_message(text1[:],text2)
print_list(text1)
print_list(text2)
形参前面加一个星号*代表让Python创建一个名为该形参的空元组,并将函数收到的所有值都封装进该元组中。
此时可以让函数收集任意数量个实参。
def method(*value)
下面的代码将打印不同类型的披萨,因为不知道有几种披萨需要制作,因此将不同的topping设置为未知量,在调用函数时可以添加未知个数的披萨toppings,这些toppings会被存储在一个元组中。
def make_pizza(*toppings):
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print(f"{topping.title()}")
make_pizza('pepperroni')
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.title()}")
make_pizza(12,'pepperroni')
make_pizza(16,'mushrooms', 'green peppers', 'extra cheese')
让函数接收任意键值对:使用双星号**形参名代表让Python创建一个名为该形参名的空字典,并将收到的所有键值对放进该字典中。
def method ( arg1, arg2, **info )
Python将为函数创建一个名为info的字典,并将所有的键值对都存储进去。
def build_profile(first_name,last_name,**user_info):
user_info['first_name'] = first_name
user_info['last_name'] = last_name
return user_info
user_profile = build_profile('amy','ma',city = 'zibo',age = 28,major='computer and science')
print(user_profile)
对上述代码进行debug,可以看到创建的字典中包含了5个键值对,可以看到字典中的键值对顺序是先定义函数中自己输入的键值对,然后才是函数中定义的形参。
输出如下所示。
def make_pizza(*toppings):
for topping in toppings:
print(f"The pizza is made of {topping.title()}")
def build_profile(f_name,l_name,**info):
info['first name'] = f_name
info['last name'] = l_name
return info
def make_car(maker,type,**info):
info['maker'] = maker
info['type'] = y=type
return info
print('8-12')
make_pizza('1')
make_pizza('2','3')
make_pizza('34')
print('8-13')
my_profile = build_profile('weiyi','ma',city = 'zibo',major = 'cs', university = 'SHU')
for k,v in my_profile.items():
print(f"My {k.title()} is {v.title()}")
print('8-14')
car = make_car('subaru', 'outback', color='blue', tow_package=True)
print(car)
可以将函数存储在称为模块的独立文件中,再将模块导入(import)到主程序中。
语法: import 模块名
1. 创建模块:pizza.py为一个包含make_pizza函数的文件。
2. 调用该模块:在main.py中调用make_pizza模块。
语法:module_name.function_name()
语法: from module_name import function_name
用逗号分隔函数名:从模块中导入任意数量的函数:
语法:from module_name import function_0, function_1, function_2
from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
函数名太长时可以使用as关键字为其起一个别名。
语法:from module_name import function_name as fn
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
语法:import module_name as mn
import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
语法:from module_name import *
from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')