python基础7

函数

基于目前微薄的知识储存,我将python基础知识分为两个方向,横向和纵向。

横向:变量-列表-字典

纵向:变量-函数-类

在变量层次的列表-字典的操作我们已经学习过了,本章学习函数的基础知识及其与字典、列表的结合。

函数基础

最简形式函数

函数 是带名字的代码块。

即函数是对代码块命名,以便重复使用该代码块。

对比记忆,变量不就是带名字的数据(数值、字符串等)。

这一节很考验理解,而且目前而言,我也只是稍微理解了一下,还不太容易以简单直接的方式将自己的理解表达出来,因此,首先来几个最简单的例子,开开胃,自己理解一下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# _*_ coding: utf-8_*_
def gree_user():
"""定义函数,显示简单问候语"""
print("Hello!")

gree_user()
"""-----------------------------"""


def gree_user(username):
"""定义函数,显示简单问候语"""
print("Hello,"+username.title()+"!")


gree_user('Johnkou')
"""-----------------------------"""


def favorite_book(title):
"""定义最爱的书"""
print(
"One of my favorite books is "+title.title()
)


favorite_book("Alice in wonderland")

形参与实参

形参:函数完成其工作所需的一项信息。

实参:调用函数时传递给函数的信息。

  1. 无默认值情况
1
2
3
4
5
6
7
8
9
10
11
12
13
def describe_animal(animal_type, pet_name):
# 如animal_type, pet_name为形参
""""传递实参的几种方式"""
print("\nI have a " + animal_type + ".")
print("\nMy " + animal_type +
"'s name is " + pet_name + ".")


describe_animal("dog", "mingming")
# 顺序实参,必须注意参数顺序
describe_animal(animal_type="dog", pet_name="mingming")
# 关键字实参,无需注意实参顺序
describe_animal(pet_name="mingming", animal_type="dog")
  1. 有默认值情况
1
2
3
4
5
6
7
8
9
10
11
12
13
14
def describe_animal(animal_type, pet_name="xiongmao"):  

""""此处对pet_name添加了默认值,传递实参的几种方式"""
print("\nI have a " + animal_type + ".")
print("\nMy " + animal_type + "'s name is " + pet_name + ".")


describe_animal("dog")
# 在设置默认值的情况下,可以只对一个实参进行传递
describe_animal("dog", "mingming")
# 顺序实参,必须注意参数顺序,可以代替默认值
describe_animal(animal_type="dog", pet_name="mingming")
# 关键字实参,无需注意实参顺序
describe_animal(pet_name="mingming", animal_type="dog")

函数进阶

返回值

函数中不仅仅有print(),更重要甚至更常见的是返回值return

  1. 返回简单值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def get_formatted_name(first_name, last_name):
"""返回整洁的名字"""
full_name = first_name + ' ' + last_name
return full_name.title()


formatted_names = []

while True:
print("please enter your name below.")
f_name = input("First name:")
l_name = input("Last name:")

form_name = get_formatted_name(f_name, l_name)
formatted_names.append(form_name)

tips = input('Enter "quit" to leave!')
if tips == "quit":
break

print(formatted_names)
  1. 返回字典
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def build_person(first_name, last_name):
"""返回字典"""
person = {'first': first_name, 'last': last_name}
return person


musician = build_person('jimi', 'hendrix')
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('jimi', 'hendrix', 23)
print(musician)
'''------------------------------------------'''
{'first': 'jimi', 'last': 'hendrix'}
{'first': 'jimi', 'last': 'hendrix', 'age': 23}

传递列表

传递列表,不是将函数值返回到列表中,而是将已有列表中的值作为函数的输入来处理。

  1. 向列表中用户发送问候
1
2
3
4
5
6
7
8
9
# 向列表中用户发送问候

def greet_users(names):
"""函数可以直接处理列表,无需将列表中变量提取出来"""
for name in names:
print("Hello, "+name+"!")

users = ['ss','ee','rr','gg']
greet_users(users)
  1. 待处理事件处理完毕后存储在已处理列表
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
"""
将带处理的表格依次处理并传送到已处理列表
"""
# 不使用函数的做法
undeal_lists = ['one', 'two', 'three']
deal_lists = []

while undeal_lists:
thing = undeal_lists.pop(0)
print("deal with "+thing)
deal_lists.append(thing)

print(deal_lists)
"""
# 不能在for循环中修改列表,以下为错误循环。
for thing in undeal_lists:
print(thing)
things = undeal_lists.remove(thing)
print(things)
deal_lists.append(thing)
print(deal_lists)
print(undeal_lists)
"""
"""--------------------------------"""
deal with one
deal with two
deal with three
['one', 'two', 'three']
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 使用函数的做法
# 使用函数
def dealist(undeal_lists, deal_lists):
while undeal_lists:
thing = undeal_lists.pop(0)
print("deal with "+thing)
deal_lists.append(thing)
print(deal_lists)


undeal_lists = ['one', 'two', 'three']
deal_lists = []

dealist(undeal_lists, deal_lists)
"""---------------------------------"""
deal with one
deal with two
deal with three
['one', 'two', 'three']
  1. 禁止函数修改列表

本质上就是使用切片法,在函数中创建待处理列表的副本,所有活动在副本中进行,以不影响原始列表的变化。

传递任意数量的实参(*)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def make_pizza(*toppings):
"""一个形参"""
print(toppings)

make_pizza('ss', 'ss', 'ee', 'ff')

def make_pizza(size, *toppings):
"""结合使用位置实参和任意数量实参"""
print(str(size)+" size pizza need toppings below:")
for topping in toppings:
print("\t"+topping)

make_pizza(34, 'pepperoni', 'mushrooms', 'green peppers')

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='princeton'field='physics')
print(user_profile)

----------------------------------------------
{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}

将函数存储在模块中

函数的优点之一是,使用它们可以将代码块与主程序分离。通过给函数指定描述性名称,可让主程序容易理解。

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

通过将函数存储在独立的文件中,可隐藏程序代码的细节,将重点放在程序的高层逻辑上。

  1. 导入模块的方法

将函数代码对立存储在一个文件中,这个文件便可被成为模块.

如将以下函数独立存储并命名为pizza.py。

1
2
3
4
5
6
7
def make_pizza(size, *toppings):
"""结合使用位置实参和任意数量实参"""
print(str(size)+" size pizza need toppings below:")
for topping in toppings:
print("\t"+topping)

make_pizza(34, 'pepperoni', 'mushrooms', 'green peppers')

在主程序中导入该模块的方法为:

1
2
3
4
5
6
7
8
9
10
11
12
13
import pizza
pizza.make_pizza(23,'pep', 'mushroom')

import pizza as pa
pa.make_pizza(23,'pep'.'mushroom')

import make_pizza from pizza
make_pizza(23,'pep'.'mushroom')

import * from pizza
# 导入该模块中的所有的函数,但是一般不会如此使用
# 最好还是使用完全限定方式表示函数,以便理解
make_pizza(23,'pep'.'mushroom')

函数编写指南

  • 应该函数描述性名称,且只在其中使用小写字母和下划线。

    描述性名称可以帮助自己和他人理解代码想要做什么。
    给模块命名也应如此

  • 每个函数都应包含简要的阐述其功能的注释,该注释紧跟函数名之后,并采用文档字符串的格式。

    文档良好的函数让其他程序员只需阅读文档字符串中的描述就能够使用它们。

  • 给形参指定默认值时,等号两边不要有空格。对于函数调用的关键词实参也应如此。

  • 建议代码行的长度不超过79个字符。如果形参很多,可以在回车缩进在下一行形参开始处继续编写。

  • 如果程序包含多个函数,可使用两个空行将相邻的函数分开,这样更容易理解函数的起始位置。


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!