python基础入门----函数

Python Functions

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.

Table of Contents

  • What is a function in Python?
    • Syntax of Function
    • Example of a function
    • How to call a function in python?
  • Docstring
  • The return statement
    • Syntax of return
    • Example of return
  • How Function works in Python?
  • Scope and Lifetime of variables
  • Types of Functions

python函数

在这篇文章中,你可以学习到函数;什么是函数,语法,组成和一个函数类型。还有,你可以学习创建一个函数在python中。

表格内容

  • 什么是函数?
  1. 函数语法
  2. 函数例子
  3. 在python中如何调用一个函数
  • 文档字符
  • return语句
  1. return语法
  2. return例子
  • 函数如何工作
  • 变量的一生(生命周期)和范围
  • 函数类型

What is a function in 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里,函数是一个组合关系的语句,执行特殊任何。

函数可以帮助我们打破我们程序分解成更小的模块。当我们的程序变得越来越大,函数能使它更有组织性和管理性。

此更多的,她避免了重复和是代码更有用。


Syntax of Function

def function_name(parameters):
	"""docstring"""
	statement(s)

Above shown is a function definition which consists of following components.

  1. Keyword def marks the start of function header.
  2. A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in Python.
  3. Parameters (arguments) through which we pass values to a function. They are optional.
  4. A colon (:) to mark the end of function header.
  5. Optional documentation string (docstring) to describe what the function does.
  6. One or more valid python statements that make up the function body. Statements must have same indentation level (usually 4 spaces).
  7. An optional return statement to return a value from the function.

函数语法

>>> def function_name(parameters):
...     """dosctring"""
...     statement(s)
...

上面显示一个函数的定义和组件组成在下面展示。

  1. 关键字def标志这一个函数头部的开始。 
  2. 一个函数名是唯一特征辨认它。函数名和python编写特征规则一样。
  3. 参数(参数),我们通过将值传给一个函数。他们是可选的。
  4. 一个冒号(:)是标志着函数头部的结束。
  5. 可选的文档字符串(docstring)去描述函数在做什么。
  6. 一个或多个有效python语句组成函数主体。语句必须有相同的缩进(通常是4个)。
  7. 一个可选renturn语句是函数返回一个值。

Example of a function

def greet(name):
	"""This function greets to
	the person passed in as
	parameter"""
	print("Hello, " + name + ". Good morning!")

How to call a function in python?

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里尝试执行上面代码 可以看到输出。


Docstring

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

The return statement is used to exit a function and go back to the place from where it was called.

Syntax of return

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语句是用来退出一个函数并退回原来的那个它被调用的地方。

return 语法

 

>>> return [expression_list]

 这个语句包含了获取计算返回的值的表达式。如果语句表达式这里没有表达式或return语句自己不在当前函数里面,然后函数将会返回None类型。

例如:

>>> print(greet("May"))
Hello, May. Good morning!
None

这里,None是返回值。 


Example of return

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

return例子

 

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

How Function works in Python?

函数如何工作?

python基础入门----函数_第1张图片


Scope and Lifetime of variables

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。


Types of Functions

Basically, we can divide functions into the following two types:

  1. Built-in functions - Functions that are built into Python.
  2. User-defined functions - Functions defined by the users themselves.

函数类型

基本上,我们可以把函数分为下面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

  • PREVIOUS 
    PYTHON LOOPING TECHNIQUES
  • NEXT 
    PYTHON FUNCTION ARGUMENTS

你可能感兴趣的:(python3)