In this article, you'll learn about functions; what is a function, the syntax, components and types of a function. Also, you'll learn to create a function in Python.
在这篇文章中,你可以学习到函数;什么是函数,语法,组成和一个函数类型。还有,你可以学习创建一个函数在python中。
In Python, function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes code reusable.
在python里,函数是一个组合关系的语句,执行特殊任何。
函数可以帮助我们打破我们程序分解成更小的模块。当我们的程序变得越来越大,函数能使它更有组织性和管理性。
此更多的,她避免了重复和是代码更有用。
def function_name(parameters):
"""docstring"""
statement(s)
Above shown is a function definition which consists of following components.
def
marks the start of function header.return
statement to return a value from the function.>>> def function_name(parameters):
... """dosctring"""
... statement(s)
...
上面显示一个函数的定义和组件组成在下面展示。
def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")
Once we have defined a function, we can call it from another function, program or even the Python prompt. To call a function we simply type the function name with appropriate parameters.
>>> greet('Paul')
Hello, Paul. Good morning!
Note: Try running the above code into the Python shell to see the output.
一旦我们定义了一个函数,我们可以从另外一个函数,程序或甚至python提示符调用它。去调用一个函数,我们只要简单的代入适当参数到函数模型里。
>>> def greet(name):
... """This function greets to the person passed in as parameter"""
... print("Hello, " + name + ". Good morning!")
...
>>> greet('Paul')
Hello, Paul. Good morning!
注意:在python shell里尝试执行上面代码 可以看到输出。
The first string after the function header is called the docstring and is short for documentation string. It is used to explain in brief, what a function does.
Although optional, documentation is a good programming practice. Unless you can remember what you had for dinner last week, always document your code.
In the above example, we have a docstring immediately below the function header. We generally use triple quotes so that docstring can extend up to multiple lines. This string is available to us as __doc__
attribute of the function.
For example:
Try running the following into the Python shell to see the output.
>>> print(greet.__doc__)
This function greets to
the person passed into the
name parameter
函数头部后面的第一个行字符串叫做文档字符串,全称是文档字符串。它用来做简单的解释,一个函数做什么。
虽然可选,文档是一个很好的程序实践。除非你能记住你上一周的晚餐,不然你的代码总是要有文档的。
上面的例子,我们有函数头部下面立刻有一个文档字符串。我们一般使用三倍引号因此文档字符串能延迟为多行。这字符串是作为__doc__函数的属性提供给我们。
例如:
在python shell尝试执行得到下面看到的输出。
>>> print(greet.__doc__)
This function greets to the person passed in as parameter
The return
statement is used to exit a function and go back to the place from where it was called.
return [expression_list]
This statement can contain expression which gets evaluated and the value is returned. If there is no expression in the statement or the return
statement itself is not present inside a function, then the function will return the None
object.
For example:
>>> print(greet("May"))
Hello, May. Good morning!
None
Here, None
is the returned value.
这return语句是用来退出一个函数并退回原来的那个它被调用的地方。
>>> return [expression_list]
这个语句包含了获取计算返回的值的表达式。如果语句表达式这里没有表达式或return语句自己不在当前函数里面,然后函数将会返回None类型。
例如:
>>> print(greet("May"))
Hello, May. Good morning!
None
这里,None是返回值。
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num
# Output: 2
print(absolute_value(2))
# Output: 4
print(absolute_value(-4))
>>> def absolute_value(num):
... """This function returns the absolute value of the entered number"""
... if num >= 0:
... return num
... else:
... return -num
...
>>> print(absolute_value(2))
2
>>> print(absolute_value(-4))
4
Scope of a variable is the portion of a program where the variable is recognized. Parameters and variables defined inside a function is not visible from outside. Hence, they have a local scope.
Lifetime of a variable is the period throughout which the variable exits in the memory. The lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function. Hence, a function does not remember the value of a variable from its previous calls.
一个变量的作用域是识别部分程序变量。参数和变量定义在一个函数里面,从外面是不可看到的。因此,它们是一个局部模块。
一个变量的生命周期是变量存在内存的期间。变量的生命周期是存在一个函数里面,只要函数被执行。
他们被摧毁一旦我们返回这函数。因此,一个函数不会记住一个变量的值之前被调用过。
Here is an example to illustrate the scope of a variable inside a function.
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Output
Value inside function: 10
Value outside function: 20
这是一个例子,去解释一个变量在函数里边的作用范围。
输出:
>>> def my_func():
... x = 10
... print("Value inside function:",x)
...
>>> x = 20
>>> my_func()
Value inside function: 10
>>> print("Value outside function:",x)
Value outside function: 20
Here, we can see that the value of x is 20 initially. Even though the function my_func()
changed the value of x to 10, it did not effect the value outside the function.
This is because the variable x inside the function is different (local to the function) from the one outside. Although they have same names, they are two different variables with different scope.
On the other hand, variables outside of the function are visible from inside. They have a global scope.
We can read these values from inside the function but cannot change (write) them. In order to modify the value of variables outside the function, they must be declared as global variables using the keyword global
.
这里,我们可以看到这个x的值最初是20 。尽管在函数my_func()里变量x改变为10,它不影响外面的值。
这是因为x变量在函数里面和外面那个(局部函数)是不同的。虽然他们有相同的名字,他们有在不同的作用域2个不同的变量。
我们能读取这些值从里面的函数,但是不能改变(写)他们。为了改变外面函数变量的值,他们必须声明作为全局变量,使用关键字global。
Basically, we can divide functions into the following two types:
基本上,我们可以把函数分为下面2种类型:
1.内置函数--python中的内置函数。
2.用户自定义函数--用户自己定义函数。
Check out these examples to learn more:
Python Program to Find HCF or GCD
Python Program to Find LCM
Python Program to Make a Simple Calculator