《Python编程从入门到实践》_第八章_函数

《Python编程从入门到实践》_第八章_函数

print("8.1定义函数")
def greet_user():
    print("hello!")
greet_user()

def greet_user(username):
    print("Hello, " + username.title() + "!")
greet_user('Mars')
# 在函数greet_user的定义中,变量username是一个形参——函数完成其工作所需的一项信息。
# 在代码greet_user('Mars')中,其'Mars'就是一个实参,实参是调用函数时传递给函数的信息。
print("8.2 传递实参")
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('hamster', 'harry')
describe_pet('dog', 'wii')
describe_pet("dog", "gii")
print("8.2.2关键字实参")
print("可以直接将形参和实参关联起来,这样就不必要在意顺序了。")
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet( pet_name='harry',animal_type='hamster')
print("8.2.3默认值")
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(pet_name = 'ggii')
describe_pet('aggii')
# 由于显示的给提供了实参 就会忽略给定形参的默认值
describe_pet(animal_type='hamster', pet_name='harry')
print("8.2.4 等效的函数调用")
def describe_pet(pet_name,animal_type = 'dog'):
    print("I have a " + animal_type + ". ")
    print("My " + animal_type + "'s name is "+ pet_name.title() + ".")
# 一条名为dd的小狗
describe_pet('aa')
describe_pet(pet_name='cc')
# 一只名为haa的仓鼠
describe_pet('haa','hamster')
describe_pet(pet_name='haa',animal_type='hamster')
describe_pet(animal_type='hamster',pet_name='haa')
#########################################################################################
C:\Anaconda3\python.exe H:/python/venv/text
8.1定义函数
hello!
Hello, Mars!
8.2 传递实参
I have a hamster. 
My hamster's name is Harry.
I have a dog. 
My dog's name is Wii.
I have a dog. 
My dog's name is Gii.
8.2.2关键字实参
可以直接将形参和实参关联起来,这样就不必要在意顺序了。
I have a hamster. 
My hamster's name is Harry.
I have a hamster. 
My hamster's name is Harry.
8.2.3默认值
I have a dog. 
My dog's name is Ggii.
I have a dog. 
My dog's name is Aggii.
I have a hamster. 
My hamster's name is Harry.
8.2.4 等效的函数调用
I have a dog. 
My dog's name is Aa.
I have a dog. 
My dog's name is Cc.
I have a hamster. 
My hamster's name is Haa.
I have a hamster. 
My hamster's name is Haa.
I have a hamster. 
My hamster's name is Haa.

Process finished with exit code 0
#########################################################################################
print("8.3返回简单值")
def get_formatted_name(first_name, last_name):
    full_name = first_name + " " + last_name
    return full_name.title()
print("函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数返回的值被称为返回值")
musician = get_formatted_name('jimi','hendrix')
print(musician)
print("8.3.2让实参变为可选的")
def get_formatted_name(first_name, middle_name, last_name):
    full_name = first_name + " " + middle_name + " " + last_name
    return full_name.title()
musician = get_formatted_name('jimi','lee', 'hendrix')
print(musician)
def get_formatted_name(first_name, last_name, middle_name=''):
    full_name = first_name + " " + middle_name + " " + last_name
    return full_name.title()
musician = get_formatted_name('jimi','hendrix')
print(musician)
musician = get_formatted_name('jimi', 'lee', 'hendrix')
print(musician)
print("8.3.3返回字典")
def build_person(first_name, last_name):
    person = {'first': first_name, 'last': last_name}
    return person
musician = build_person('jim', 'aa')
print(musician)
def build_person(first_name, last_name, age = ''):
    person = {'first': first_name, 'last': last_name}
    if age:
        person['age'] = age
    return person
musician = build_person('jim', 'aa',age=27)
print(musician)
print("8.3.4结合使用while循环和函数")
while True:
    print("please 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
    formatted_name = get_formatted_name(f_name, l_name)
    print("Hello, " + formatted_name + "!")
######################################################################################
C:\Anaconda3\python.exe H:/python/venv/text
8.3返回简单值
函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数返回的值被称为返回值
Jimi Hendrix
8.3.2让实参变为可选的
Jimi Lee Hendrix
Jimi  Hendrix
Jimi Hendrix Lee
8.3.3返回字典
{'first': 'jim', 'last': 'aa'}
{'first': 'jim', 'last': 'aa', 'age': 27}
8.3.4结合使用while循环和函数
please tell me your name: 
(enter 'q' at any time to quit)
First name: Mars
Last name: Liu
Hello, Mars  Liu!
please tell me your name: 
(enter 'q' at any time to quit)
First name: q

Process finished with exit code 0
########################################################################################
print("8.4传递列表")
def greet_users(names):
    for name in names:
        msg = "Hello, " + name.title() + "!"
        print(msg)

usernames=['a', 'b', 'c']
greet_users(usernames)
print("8.4.1在函数中修改列表")
def  print_models(upprint,completed):
    '''
    弹出已打印的给完成的列表,并打印
    '''
    while upprint:
        current = upprint.pop()
        print("print:", current)
        completed.append(current)
def show_models(completed):
    '''
    显示已打印的
    '''
    print("The following models have been print:")
    for c in completed:
        print(c)
upprint = ["apple", "book", "shirt"]
completed = []
print_models(upprint, completed)
show_models(completed)
# 在这个例子中,函数执行结束后,
# upprint列表就空了,为了解决这个问题,
# 可向函数传递列表的副本而不是原件,这样函数所做的任何修改都只影响副本,而不会影响原件
print(upprint) # 发现运行之后upprint列表就空了
# 切片表示法[:],创建列表副本。
upprint = ["apple", "book", "shirt"]
completed = []
print_models(upprint[:], completed)
show_models(completed)
print(upprint)
# 发现运行之后upprint列表还是原样
# 虽然向函数传递列表的副本可以保留原始的列表的内容,但除非有充分的理由需要传递副本,
# 否则还是应该讲原始数据传递给函数,因为让函数使用现成列表可以避免花时间和内存创建副本
# 从而提高效率,在处理大型列表时尤其如此。
print("8.5 传递任意数量的实参")
print("有时候,你预先不知道函数需要接受多少个实参,好在Python允许函数从调用语句中收集任意数量的实参:")
print("形参名*toppings的星号让Python创建一个名为toppings的空元祖,并将收到的所有值都封装想到这个元组中。")
def make_pizza(*toppings):
    # 概述要制作的pizza
    print("\nMaking a pizza with the following toppings:")
    for topping in toppings:
        print("--", topping)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
print("8.5.1结合使用位置实参和任意数量实参")
def make_pizza(size,*toppings):
    # 概述要制作的pizza
    print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
    for topping in toppings:
        print("--", topping)
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'grenn peppers', 'extra cheese')
print("8.5.2使用任意数量的关键字实参")
# 在下面的例子中,函数build_profile()接收名和姓,同时还接收任意数量的关键字和实参:
# **info中的两个星号让python创建一个空字典,将收到的所有名称-值对都封装到这个字典里
def build_profile(first_name, last_name, **info):
    # 创建一个字典,其中包含我们知道的有关用户的一切
    profile = {}
    profile["first_name"] = first_name
    profile["last_name"] = last_name
    for key, value in info.items():
        profile[key] = value
    return profile
user_profile = build_profile("bin","liu",location="princeton",field="physics")
# location="princeton",field="physics"两个键-值对
print(user_profile)
#########################################################################################
C:\Anaconda3\python.exe H:/python/venv/text
8.4传递列表
Hello, A!
Hello, B!
Hello, C!
8.4.1在函数中修改列表
print: shirt
print: book
print: apple
The following models have been print:
shirt
book
apple
[]
print: shirt
print: book
print: apple
The following models have been print:
shirt
book
apple
['apple', 'book', 'shirt']
8.5 传递任意数量的实参
有时候,你预先不知道函数需要接受多少个实参,好在Python允许函数从调用语句中收集任意数量的实参:
形参名*toppings的星号让Python创建一个名为toppings的空元祖,并将收到的所有值都封装想到这个元组中。

Making a pizza with the following toppings:
-- pepperoni

Making a pizza with the following toppings:
-- mushrooms
-- green peppers
-- extra cheese
8.5.1结合使用位置实参和任意数量实参

Making a 16-inch pizza with the following toppings:
-- pepperoni

Making a 12-inch pizza with the following toppings:
-- mushrooms
-- grenn peppers
-- extra cheese
8.5.2使用任意数量的关键字实参
{'first_name': 'bin', 'last_name': 'liu', 'location': 'princeton', 'field': 'physics'}

Process finished with exit code 0
#########################################################################################
# pizza.py 例子:先创建一个打印方式make_pizza.py
#pizza打印方式模块
def make_pizza1(size,*toppings):
    # 概述要制作的pizza
    print("\n Making a " + str(size) +
          "-inch pizza with the following toppings:")
    for topping in toppings:
        print("----" + topping)
def make_pizza2(size,*toppings):
    # 概述要制作的pizza
    print("\nsize:",size)
    print("toppings:")
    for topping in toppings:
        print("====",topping)
##############################################################
# import pizza
# from pizza import make_pizza1, make_pizza2
# pizza.make_pizza1(16,'pepperoni','mushrooms')
# pizza.make_pizza2(16,'pepperoni','mushrooms')
# 要调用被导入的模块中的函数,可指定导入模块的名称make_pizza和函数名make_pizza1(),并用句点来分割他们。
# 这就是一种导入方法,只需编写一条import语句并在其中指定模块名,就可以在程序中使用该模块中的所有函数
# make_pizza1(16, 'pepperoni', 'mushrooms')
# make_pizza2(16, 'pepperoni', 'mushrooms')
print("8.6.4使用as给模块定义别名")
# import pizza as p
# p.make_pizza1(16, 'pepperoni')
# p.make_pizza2(15,'pepperoni', 'mushrooms')
print("语法:from module_name import function_name as fn")
print("8.6.3使用as给函数定义别名")
# 给模块指定别名的通用语法如下
print("语法:from module_name import function_name as fn")
#pizza
# from pizza import make_pizza1 as pz1, make_pizza2 as pz2
# pz1(16, 'pepperoni', 'mushrooms')
# pz2(16, 'pepperoni', 'mushrooms')
print("8.6.5导入模块中所有的函数")
print(" *可以代表前面指定模块里的所有函数")
from pizza import *
make_pizza1(16, 'pepperoni')
make_pizza2(15,'pepperoni', 'mushrooms')
######################################################################
C:\Anaconda3\python.exe H:/python/venv/text
8.6.4使用as给模块定义别名
语法:from module_name import function_name as fn
8.6.3使用as给函数定义别名
语法:from module_name import function_name as fn
8.6.5导入模块中所有的函数
 *可以代表前面指定模块里的所有函数

 Making a 16-inch pizza with the following toppings:
----pepperoni

size: 15
toppings:
==== pepperoni
==== mushrooms

Process finished with exit code 0
#####################################################################################3
给形参指定默认值时,等号两边不要有空格
def function_name(parameter_0, parameter_1='default value')
对于函数调用中的关键字实参 也遵循这种约定
function_name(value_0,parameter_1='value')

猜你喜欢

转载自blog.csdn.net/weixin_40807247/article/details/82081105