读书笔记「Python编程:从入门到实践」_8.函数

8.1 定义函数

def greet_user():        # def 来告诉Python你要定义一个函数。这是函数定义
    """Hello World"""    # 文档字符串 (docstring)Python使用它们来生成有关程序中函数的文档。
    print("Hello!")

greet_user()             # 函数调用

  8.1.1 向函数传递信息

def greet_user(username):
    """显示简单的问候语"""
    print("Hello, " + username.title() + "!")
greet_user('chang')

  8.1.2 实参和形参

  形参 变量。username 是一个形参 ——函数完成其工作所需的一项信息。

  实参 实际信息。调用函数时传递给函数的信息。在代码greet_user('jesse') 中,值'jesse' 是一个实参 。

8.2 传递实参

  位置实参 ,这要求实参的顺序与形参的顺序相同;

  关键字实参 ,其中每个实参都由变量名和值组成;

  还可使用列表和字典。

  8.2.1 位置实参 顺序对应

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', 'harry')

  8.2.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(animal_type='dog', pet_name='harry')
describe_pet(pet_name='tom', animal_type='cat'
I have a dog.
My dog's name is Harry.
I have a cat.
My cat's name is Tom.

  8.2.3 默认值

  使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的实参。这让Python依然能够正确地解读位置实参。

  使用关键字实参的时候,顺序无关。

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='willie')
describe_pet('tom')
describe_pet(pet_name='jerry',animal_type='cat')
describe_pet(animal_type='cat',pet_name='jerry')
I have a dog.
My dog's name is Willie.
I have a dog.
My dog's name is Tom.
I have a cat.
My cat's name is Jerry.
I have a cat.
My cat's name is Jerry.

  8.2.4 等效的函数调用

  可混合使用位置实参、关键字实参和默认值,通常有多种等效的函数调用方式。参照上例

  使用哪种调用方式无关紧要,只要函数调用能生成你希望的输出就行。使用对你来说最容易理解的调用方式即可。

  8.2.5 避免实参错误

  TypeError, describe_pet() missing 2 required positional arguments: 'animal_type' and 'pet_name'

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()

8.3 返回值

  函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数返回的值被称为返回值 。

  在函数中,可使用return 语句将值返回到调用函数的代码行。返回值让你能够将程序的大部分繁重工作移到函数中去完成,从而简化主程序。

  8.3.1 返回简单值

def get_formatted_name(first_name, last_name):
    """返回整洁的姓名"""
    full_name = first_name + ' ' + last_name
    return full_name.title()
musician = get_formatted_name('chang', 'xin')
print(musician)

  8.3.2 让实参变成可选的

  需要让实参变成可选的,这样使用函数的人就只需在必要时才提供额外的信息。可使用默认值来让实参变成可选的。

def get_formatted_name(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()
fullname = get_formatted_name('chang', 'xin')
print(fullname)
fullname = get_formatted_name('chang', 'ran', 'xi')
print(fullname)
Chang Xin
Chang Xi Ran

  8.3.3 返回字典

  函数可返回任何类型的值,包括列表和字典等较复杂的数据结构

def build_person(first_name, last_name):
    """返回一个字典,其中包含有关一个人的信息"""
    person = {'first': first_name, 'last': last_name}
    return person
personDic = build_person('chang', 'xin')
print(personDic)
{'first': 'chang', 'last': 'xin'}

   8.3.4 结合使用函数和while循环 

def get_formatted_name(first_name, last_name):
    """返回整洁的姓名"""
    full_name = first_name + ' ' + last_name
    return full_name.title()
# 这是一个无限循环!
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)

8.4 传递列表

def greet_users(names):
    """向列表中的每位用户都发出简单的问候"""
    for name in names:
        msg = "Hello, " + name.title() + "!"
        print(msg)
usernames = ['chang', 'li', 'wang']
greet_users(usernames)
Hello, Chang!
Hello, Li!
Hello, Wang!

  8.4.1 在函数中修改列表

def print_models(unprinted_designs, completed_models):
    """
    模拟打印每个设计,直到没有未打印的设计为止
    打印每个设计后,都将其移到列表completed_models中
    """
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        # 模拟根据设计制作3D打印模型的过程
        print("Printing model: " + current_design)
        completed_models.append(current_design)
def show_completed_models(completed_models):
    """显示打印好的所有模型"""
    print("
The following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)

unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case

The following models have been printed:
dodecahedron
robot pendant
iphone case

  8.4.2 禁止函数修改列表

   要将列表的副本传递给函数,可以像下面这样做:

  function_name(list_name[:])

8.5 传递任意数量的实参  形参前面加个  *

def make_pizza(*toppings):
    """概述要制作的比萨"""
    print("
Making a pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
Making a pizza with the following toppings:
- pepperoni
Making a pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

  8.5.1 结合使用位置实参和任意数量实参

def make_pizza(size, *toppings):
    """概述要制作的比萨"""
    print("
Making a " + str(size) +
    "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + 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

  8.5.2 使用任意数量的关键字实参

  形参**user_info 中的两个星号让Python创建一个名为user_info 的空字典,并将收到的所有名称—值对都封装到这个字典中。

def build_profile(first, last, **user_info):
    """创建一个字典,其中包含我们知道的有关用户的一切"""
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.items():
        profile[key] = value
    return profile
user_profile = build_profile('albert', 'einstein',
    location='china',
    field='beijing')
print(user_profile)
{'first_name': 'albert', 'last_name': 'einstein', 'location': 'china', 'field': 'beijing'}

8.6 将函数存储在模块中

  将函数存储在被称为模块 的独立文件中,再将模块导入 到主程序中。

  import 语句允许在当前运行的程序文件中使用模块中的代码。

  8.6.1 导入整个模块

  模块 是扩展名为.py的文件,包含要导入到程序中的代码。

  只需编写一条import 语句并在其中指定模块名,就可在程序中使用该模块中的所有函数。

  module_name.function_name()

  例:pizza.py

def make_pizza(size, *toppings):
    """概述要制作的比萨"""
    print("
Making a " + str(size) +
    "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

  pizza.py的引用

import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.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

  8.6.2 导入特定的函数

  from module_name import function_name

  若使用这种语法,调用函数时就无需使用句点。由于我们在import 语句中显式地导入了函数make_pizza() ,因此调用它时只需指定其名称。

from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

  8.6.3 使用as给函数指定别名

  如果要导入的函数的名称可能与程序中现有的名称冲突,或者函数的名称太长,可指定简短而独一无二的别名 ——

  函数的另一个名称,类似于外号。要给函数指定这种特殊外号,需要在导入它时这样做。

  关键字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')


  8.6.4 使用as给模块指定别名

  你还可以给模块指定别名。

  通过给模块指定简短的别名(如给模块pizza 指定别名p ),让你能够更轻松地调用模块中的函数。

  相比于pizza.make_pizza(),p.make_pizza() 更为简洁

  import module_name as mn

import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

  8.6.5 导入模块中的所有函数

  使用星号(* )运算符可让Python导入模块中的所有函数:

  可通过名称来调用每个函数,而无需使用句点表示法。然而,使用并非自己编写的大型模块时,最好不要采用这种导入方法:

  如果模块中有函数的名称与你的项目中使用的名称相同,可能导致意想不到的结果:

  Python可能遇到多个名称相同的函数或变量,进而覆盖函数,而不是分别导入所有的函数。

     最佳的做法是,

  要么只导入你需要使用的函数,要么导入整个模块并使用句点表示法。  

from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

8.7 函数编写指南

  ・函数指定描述性名称,且只在其中使用小写字母和下划线。
  ・每个函数都应包含简要地阐述其功能的注释,该注释应紧跟在函数定义后面,并采用文档字符串格式。
  ・给形参指定默认值时,等号两边不要有空格,对于函数调用中的关键字实参,也应遵循这种约定。
  ・如果程序或模块包含多个函数,可使用两个空行将相邻的函数分开
  ・所有的import 语句都应放在文件开头,唯一例外的情形是,在文件开头使用了注释来描述整个程序。
  ・代码行的长度不要超过79字符,这样只要编辑器窗口适中,就能看到整行代码。如果形参很多,导致函数定义的长度超过了79字符,
      可在函数定义中输入左括号后按回车键,并在下一行按两次Tab键,从而将形参列表和只缩进一层的函数体区分开来。

 

原文地址:https://www.cnblogs.com/changxinblog/p/9944732.html