-
自定义函数
除了python自带的函数,还可使用def来自己定义函数。
- 自定义名为my_func的函数,不需输入任何参数,当调用它时,会输出三次spam:
def my_func():
print("spam")
print("spam")
print("spam")
调用该函数:
my_func()
输出结果为:
spam
spam
spam
每个函数中的代码块都以冒号(:)开始并缩进
- 自定义需输入一个参数的函数,例如:
def print_with_exclamation(word):
print(word + "!")
print_with_exclamation("spam")
print_with_exclamation("eggs")
print_with_exclamation("python")
输出结果为:
spam!
eggs!
python!
- 自定义需输入多个参数的函数,以逗号分隔多个参数,例如:
def print_sum_twice(x, y):
print(x + y)
print(x + y)
print_sum_twice(5, 8)
输出结果为:
13
13
- 函数的参数可为变量,但不可在函数外引用,只可在函数内引用、赋值,例如:
def function(variable):
variable += 1
print(variable)
function(7)
print(variable)
输出结果为:
8
- 使用return返回自定义函数值的赋值,只能在函数内使用,例如:
def max(x, y):
if x >=y:
return x
else:
return y
调用该函数:
print(max(4, 7))
z = max(8, 5)
print(z)
输出结果为:
7
8
- return之后的语句都不会被执行,例如:
def add_numbers(x, y):
total = x + y
return total
print("This won't be printed")
调用该函数:
print(add_numbers(4, 5))
输出结果为:
9
- 注释(#)
- 使用#表示注释,python中修饰需在一行内,#后面的语句不会被执行,注释的加入也不会影响程序的运行,例如:
x = 365
y = 7
# this is a comment
print(x % y) # find the remainder
#print (x // y)
#another comment
输出结果为:
1
- Docstrings(文档字符串)也用于注释作用,但它可多行,位于自定义函数第一行的下面,例如:
def shout(word):
"""
Print a word with an
exclamation mark following it.
"""
print(word + "!")
调用该函数:
shout("spam")
输出结果为:
spam!
- 将函数赋值到变量
- 将自定义的函数赋值到一个变量,调用该变量时,则该变量也具有该函数的功能,例如自定义函数multiple:
def multiply(x, y):
return x * y
将自定义函数赋值到变量operation,并调用operation:
a = 4
b = 7
operation = multiply
print(operation(a, b))
输出结果为:
28
- 函数还可作为另一函数中的项来使用,例如:
def add(x, y):
return x + y
def do_twice(func, x, y):
return func(func(x, y), func(x, y))
a = 5
b = 10
print(do_twice(add, a, b))
输出结果为:
30
- Modules模块
- 模块是别人已经写好的通用代码,例如产生随机数、加减运算等,若要在自己的代码中调用某一模块,需在首行加上import module_name,然后使用module_name.var来调用模块中的函数及变量数值var,例如一下为调用产生随机数的模块来产生随机数:
import random
for i in range(5):
value = random.randint(1, 6)
print(value)
输出结果为:
2
3
6
5
4
- 在模块调用中,使用import功能可以调用模块中某一函数功能,调用方式为from module_name import var,之后便可直接使用自己未曾定义过的var变量了,例如要从math模块中调用pi:
from math import pi
print(pi)
输出结果为:
3.141592653589793
还可使用间隔一次调用多个var,例如:
from math import pi, sqrt
可使用星号调用math模块中的全部变量,但不推荐使用:
from math import *
- 调用模块或其中函数时,可使用as将其重命名,例如:
from math import sqrt as square_root
print(square_root(100))
输出结果为:
10.0
- 模块类型
- 在Python中有三种主要的模块类型,即自己写的、从外部来源安装的、Python预装的。最后一种称为标准库,并包含许多有用的模块,包括:string、re、datetime、math、random、os、multiprocessing、subprocess、socket、email、json、doctest、unittest、pdb、argparse、sys。标准库可以完成的任务包括字符串解析、数据序列化、测试、调试和操作日期、电子邮件、命令行参数等等,Python中广泛的标准库是其主要优势之一。
- 许多第三方Python模块都存储在Python包索引(PyPI)中。最好的安装方法是使用一个叫做pip的程序。这是默认安装Python的现代发行版。如果你没有它,很容易在线安装。一旦拥有它,从PyPI安装库是很容易的。查找要安装的库的名称,转到命令行,然后输入pip install library_name。完成此操作后,导入库并在代码中使用它。