介绍
函数是指令块,执行一个操作,一旦定义,可以重复使用,函数使代码更加模块化,允许您反复使用相同的代码。
Python 有许多内置的功能,您可能熟悉,包括:
print()
将对象打印到终端 *int()
将字符串或数字数据类型转换为整数数据类型 *len()
将对象的长度返回
函数名包括关节,并可能包括参数。
在本教程中,我们将讨论如何在您的编码项目中定义自己的函数。
前提条件
您应该在您的计算机或服务器上安装 Python 3 并设置一个编程环境. 如果您没有设置编程环境,可以指: [本地编程环境] (https://www.digitalocean.com/community/tutorial_series/how-to-install-and-set-up-a-local-programming-environment-for-python-3) 或适合您操作系统的 [服务器上的编程环境] (https://www.digitalocean.com/community/tutorial_collections/how-to-install-python-3-and-set-up-a-programming-environment (Ubuntu, CentOS, Debian等) 的安装和设置指南
定义一个函数
让我们先把经典的)变成一个函数。
我们将在我们所选择的文本编辑器中创建一个新的文本文件,并将该程序称为hello.py
。
一个函数是通过使用)的关节的集合,并以结肠结束。
要跟随本教程中的示例代码,请通过运行python3
命令在本地系统上打开一个Python互动壳,然后您可以复制、粘贴或编辑示例,通过在>>>
提示后添加它们。
在这种情况下,我们将定义一个名为hello()
的函数:
1[label hello.py]
2def hello():
此设置了创建函数的初始语句。
从这里开始,我们将添加一行四个空间的第二行,以提供该函数的指示,在这种情况下,我们将打印Hello, World!
到控制台:
1[label hello.py]
2def hello():
3 print("Hello, World!")
我们的函数现在已经完全定义了,但如果我们在这个时候运行该程序,就不会发生什么,因为我们没有调用该函数。
因此,在我们定义的函数块之外,让我们用hello()
来调用函数:
1[label hello.py]
2def hello():
3 print("Hello, World!")
4
5hello()
现在,让我们运行这个程序:
1python hello.py
你应该得到以下的输出:
1[secondary_label Output]
2Hello, World!
例如,我们可以使用 for
loops, 条件声明,以及更多在我们的功能块内。
例如,下方定义的函数使用条件语句来检查名称
变量的输入是否包含语音,然后使用为
循环重复名称
字符串中的字母。
1[label names.py]
2# Define function names()
3def names():
4 # Set up name variable with input
5 name = str(input('Enter your name: '))
6 # Check whether name has a vowel
7 if set('aeiou').intersection(name.lower()):
8 print('Your name contains a vowel.')
9 else:
10 print('Your name does not contain a vowel.')
11
12 # Iterate over name
13 for letter in name:
14 print(letter)
15
16# Call the function
17names()
我们上面定义的name()
函数设置了一个条件声明和一个for
循环,显示了代码如何在函数定义中进行组织,然而,取决于我们计划的意图以及我们想要如何设置我们的代码,我们可能希望将条件声明和for
循环定义为两个独立的函数。
在程序中定义函数使我们的代码模块化和可重复使用,以便我们可以调用相同的函数而不重写它们。
工作与参数
到目前为止,我们已经研究了没有参数的空格符串的函数,但我们可以在它们的符串中定义函数定义中的参数。
参数是函数定义中的命名实体,指定函数可以接受的参数。
让我们创建一个小程序,其中包括参数x
,y
和z
。我们将创建一个函数,在不同的配置中将参数合并在一起。
1[label add_numbers.py]
2def add_numbers(x, y, z):
3 a = x + y
4 b = x + z
5 c = y + z
6 print(a, b, c)
7
8add_numbers(1, 2, 3)
我们输入了1
为x
参数,2
为y
参数,3
为z
参数。
该程序基本上是基于我们传递给参数的值来做以下数学:
1a = 1 + 2
2b = 1 + 3
3c = 2 + 3
函数还打印a
,b
和c
,并根据上面的数学,我们希望a
等于3
,b
等于4
,c
等于5
。
1python add_numbers.py
1[secondary_label Output]
23 4 5
当我们将)`函数时,我们会收到预期的输出。
参数是通常在函数定义中定义为变量的参数,在运行方法时可以分配值,将参数传入函数中。
关键字论点
除了按顺序调用参数外,您可以在函数调用中使用 关键字参数 ,其中调用器通过参数名称识别参数。
当您使用关键字参数时,您可以使用不顺序的参数,因为Python解释器将使用提供的关键字来匹配参数的值。
让我们创建一个函数,将向我们显示用户的个人资料信息,我们将以)和)的形式传递参数。
1[label profile.py]
2# Define function with parameters
3def profile_info(username, followers):
4 print("Username: " + username)
5 print("Followers: " + str(followers))
在函数定义声明中,)`函数的窗格中。
现在,我们可以调用函数并分配参数:
1[label profile.py]
2def profile_info(username, followers):
3 print("Username: " + username)
4 print("Followers: " + str(followers))
5
6# Call function with parameters assigned as above
7profile_info("sammyshark", 945)
8
9# Call function with keyword arguments
10profile_info(username="AlexAnglerfish", followers=342)
在第一个函数调用中,我们用sammyshark
的用户名填写了信息,追随者是945
,在第二个函数调用中,我们使用了关键字参数,将值分配给参数变量。
让我们运行这个程序:
1python profile.py
1[secondary_label Output]
2Username: sammyshark
3Followers: 945
4Username: AlexAnglerfish
5Followers: 342
输出显示了我们两个用户的用户名和追随者的数量。
这也允许我们更改参数的顺序,如同在同一个程序的这个示例中用不同的呼叫:
1[label profile.py]
2def profile_info(username, followers):
3 print("Username: " + username)
4 print("Followers: " + str(followers))
5
6# Change order of parameters
7profile_info(followers=820, username="cameron-catfish")
当我们用python profile.py
命令重新运行该程序时,我们将收到以下输出:
1[secondary_label Output]
2Username: cameron-catfish
3Followers: 820
由于函数定义保持print()
陈述的相同顺序,如果我们使用关键字参数,那么我们将它们传入函数调用的顺序并不重要。
默认参数值
我们还可以为一个或两个参数提供默认值,让我们为followers
参数创建一个默认值,值为1
:
1[label profile.py]
2def profile_info(username, followers=1):
3 print("Username: " + username)
4 print("Followers: " + str(followers))
现在,我们可以使用仅分配的用户名函数来运行该函数,并将追随者的数目自动设置为1.我们也可以更改追随者的数目,如果我们愿意的话。
1[label profile.py]
2def profile_info(username, followers=1):
3 print("Username: " + username)
4 print("Followers: " + str(followers))
5
6profile_info(username="JOctopus")
7profile_info(username="sammyshark", followers=945)
当我们使用python profile.py
命令运行该程序时,我们将收到以下输出:
1[secondary_label Output]
2Username: JOctopus
3Followers: 1
4Username: sammyshark
5Followers: 945
提供值的默认参数可以让我们跳过每个已经具有默认值的参数的定义值。
返回值
您可以将参数值传输到函数中,并且函数也可以产生值。
函数可以使用返回
语句生成一个值,该语句将退出函数,并可选地将一个表达式传回调用人. 如果您使用没有参数的返回
语句,函数将返回无
。
到目前为止,我们在我们的函数中使用了print()
语句而不是return
语句,让我们创建一个程序,而不是打印,它会返回变量。
在一个名为square.py
的新文本文件中,我们会创建一个程序,该程序将参数x
平方并返回变量y
。
1[label square.py]
2def square(x):
3 y = x ** 2
4 return y
5
6result = square(3)
7print(result)
我们可以运行程序并接收输出:
1python square.py
1[secondary_label Output]
29
整数9
作为输出返回,这就是我们在要求Python找到3的方块时所期望的。
为了进一步了解回报
声明是如何工作的,我们可以评论程序中的回报
声明:
1[label square.py]
2def square(x):
3 y = x ** 2
4 # return y
5
6result = square(3)
7print(result)
现在,让我们再次运行程序:
1python square.py
1[secondary_label Output]
2None
在这里没有使用返回
语句,程序无法返回一个值,因此值默认值为无
。
作为另一个例子,在上面的)语句替换为
return`语句。
1[label add_numbers.py]
2def add_numbers(x, y, z):
3 a = x + y
4 b = x + z
5 c = y + z
6 return a, b, c
7
8sums = add_numbers(1, 2, 3)
9print(sums)
在函数之外,我们将变量总和
设置为等于函数以1
,2
和3
为结果,正如我们上面所做的。
现在让我们再次运行该程序,因为它有回报
声明:
1python add_numbers.py
1[secondary_label Output]
2(3, 4, 5)
我们收到相同的数字 3
, 4
,和 5
作为输出,我们之前通过使用 print()
语句在函数中收到。 这一次它是作为一个 tuple 交付,因为 return
语句的 expression list至少有一个字符串。
函数在打击返回
语句时立即退出,无论它们是否返回值。
1[label return_loop.py]
2def loop_five():
3 for x in range(0, 25):
4 print(x)
5 if x == 5:
6 # Stop function at x == 5
7 return
8 print("This line will not execute.")
9
10loop_five()
如果,相反,我们使用了 break
声明,只有循环在那个时候会退出,最后一个 `print() 行会运行。
返回语句退出函数,并且在发行与参数时可以返回值。
使用 main() 作为函数
虽然在Python中,你可以调用程序底部的函数,它会运行(正如我们在上面的例子中所做的那样),但许多编程语言(如C++和Java)需要一个主要
函数来执行。
我们将开始在上面的)函数,我们将保留我们的)
函数:
1[label hello.py]
2def hello():
3 print("Hello, World!")
4
5def main():
在 ) 语句,让我们知道我们处于 )
函数中呼叫 hello()
函数:
1[label hello.py]
2def hello():
3 print("Hello, World!")
4
5def main():
6 print("This is the main function")
7 hello()
最后,在程序的底部,我们将调用‘main()’函数:
1[label hello.py]
2def hello():
3 print("Hello, World!")
4
5def main():
6 print("This is the main function.")
7 hello()
8
9main()
此时,我们可以运行我们的计划:
1python hello.py
我们将获得以下输出:
1[secondary_label Output]
2This is the main function.
3Hello, World!
因为我们在 main() 中调用了 hello()
函数,然后只调用了 main()
来运行,所以 Hello, World!
文本只打印了一次,在告诉我们我们处于主函数的字符串之后。
接下来我们将与多个函数合作,所以值得审查 [全球和本地变量] 的变量范围(https://andsky.com/tech/tutorials/how-to-use-variables-in-python-3# global-and-local-variables)。
在Python中,‘main’是执行顶级代码的范围名称,当一个程序从标准输入、脚本或交互式提示中运行时,其‘name’设置为‘main’。
由于这个原因,有一项公约使用以下建筑:
1if __name__ == '__main__':
2 # Code to run when this is the main program here
这也允许使用程序文件:
- 作为主程序,运行
如果
声明之后的内容作为模块,而不是运行如果
声明之后的内容。
如果你正在使用你的程序文件作为一个模块,这个命令中不包含的代码在导入时也会在运行辅助文件时执行。
让我们在上面扩展我们的)`函数,以便指令在两个分散的函数。
第一個函數, has_vowel()
會檢查是否在 name
字符串中包含一個字符串。
第二个函数print_letters()
将打印name
字符串的每个字母。
1[label more_names.py]
2# Declare global variable name for use in all functions
3name = str(input('Enter your name: '))
4
5# Define function to check if name contains a vowel
6def has_vowel():
7 if set('aeiou').intersection(name.lower()):
8 print('Your name contains a vowel.')
9 else:
10 print('Your name does not contain a vowel.')
11
12# Iterate over letters in name string
13def print_letters():
14 for letter in name:
15 print(letter)
使用此设置,让我们定义‘main()’函数,该函数将包含对‘has_vowel()’和‘print_letters()’函数的调用。
1[label more_names.py]
2# Declare global variable name for use in all functions
3name = str(input('Enter your name: '))
4
5# Define function to check if name contains a vowel
6def has_vowel():
7 if set('aeiou').intersection(name.lower()):
8 print('Your name contains a vowel.')
9 else:
10 print('Your name does not contain a vowel.')
11
12# Iterate over letters in name string
13def print_letters():
14 for letter in name:
15 print(letter)
16
17# Define main method that calls other functions
18def main():
19 has_vowel()
20 print_letters()
最後,我們將在檔案底部添加「if name == 'main':' 構造。 為我們的目的,因為我們已經把所有我們想做的函數放在「main()」函數中,我們將在這個「if」聲明之後呼叫「main()」函數。
1[label more_names.py]
2# Declare global variable name for use in all functions
3name = str(input('Enter your name: '))
4
5# Define function to check if name contains a vowel
6def has_vowel():
7 if set('aeiou').intersection(name.lower()):
8 print('Your name contains a vowel.')
9 else:
10 print('Your name does not contain a vowel.')
11
12# Iterate over letters in name string
13def print_letters():
14 for letter in name:
15 print(letter)
16
17# Define main method that calls other functions
18def main():
19 has_vowel()
20 print_letters()
21
22# Execute main() function
23if __name__ == '__main__':
24 main()
现在我们可以运行这个程序:
1python more_names.py
该程序将显示与names.py
程序相同的输出,但这里的代码更有组织性,可以以模块化的方式使用,而无需修改。
如果你不想声明一个‘main()’函数,你可以这样结束程序:
1[label more_names.py]
2...
3if __name__ == '__main__':
4 has_vowel()
5 print_letters()
使用「main()」作为函数和「if name == 'main':」语句可以以逻辑的方式组织您的代码,使其更易于阅读和模块化。
结论
函数是指令的代码块,在程序中执行操作,有助于使我们的代码可重复使用和模块化。
要了解如何使您的代码更模块化,您可以阅读我们的指南在 如何在Python中编写模块 3。