用Python编写用户定义的函数

本文介绍了如何在Python中创建用户定义的函数,包括函数定义的结构、返回类型、默认参数和别名功能名称。通过示例说明了如何定义、调用函数以及使用默认参数,强调了函数在程序组织和代码复用上的优势。
摘要由CSDN通过智能技术生成

At this point, it is but obvious for you all to know what functions are! You have encountered several inbuilt functions already in the tutorials before. Although, due to all those functions being built-in, all we had to do was to use them directly by calling them and providing the required arguments if required.

在这一点上,大家都知道什么是功能! 在之前的教程中,您已经遇到了几个内置函数。 尽管由于所有这些函数都是内置的,所以我们要做的只是通过调用它们并在需要时提供所需的参数来直接使用它们。

Functions defined explicitly(by a user) in a program also helps to divide the whole program into sub-parts thereby making it more readable, easy to revise the code and to fix any errors or bugs.

程序中(由用户)明确定义的功能还有助于将整个程序划分为多个子部分,从而使其更具可读性,易于修改代码并修复任何错误或错误。

It's time to learn how we can create our own functions in python, which are also called as user-defined functions.

现在是时候学习如何在python中创建自己的函数了,这些函数也称为用户定义函数

As we have already seen in previous tutorials, to use any built-in function, we have to import the module in which the function is defined, in our program. For example, in the below program we have imported the math module to use the floor() built-in function.

正如我们在以前的教程中已经看到的那样,要使用任何内置函数,我们必须在程序中导入定义了该函数的模块。 例如,在下面的程序中,我们导入了math模块以使用floor()内置函数。

import math

a = 2.3
print ("The floor of 2.3 is : "+ math.floor(a))

If you open the module file, which is a python file only, you will be able to see the definitions of various functions, just like you would do very soon, when you will start defining your own user-defined functions.

如果打开仅是python文件的模块文件,您将能够看到各种函数的定义,就像您很快开始定义自己的用户定义函数一样。

功能定义的结构 (Structure of function definition)

Let's see how a simple function can be created. The syntax would go like,

让我们看看如何创建一个简单的函数。 语法会像

def functionName(parameter1, parameter2, ...):
    logic/algorithm statements
    ...
    return someData

The very first point here, indentation is very important, the definition of the function should be indented by a tabspace after the def functionName(parameter1, parameter2):

首先, 缩进非常重要,函数的定义应在def functionName(parameter1, parameter2):之后由制表符缩进def functionName(parameter1, parameter2):

Now let's try to understand each line one by one. The first line is called function header starts with the keyword def which actually means define, since this is the starting point from where start defining a function. Next, comes the function's name, where you give the function a name which can be, for example, say add, multiply, swap or anything which signifies what actually the function will do.

现在,让我们尝试一一理解每一行。 第一行称为函数标头 ,从关键字def开始,这实际上意味着define ,因为这是开始定义函数的起点。 接下来,是函数的名称 ,在其中给函数命名,例如,可以使用addmultipleswap或任何表示函数实际作用的名称。

Next, inside the circular braces, comes the parameters. These are some required values, which user can input, and are used inside the function during the operation. As you might remember, how we used to put several numbers while calling math's functions for example, sin(3.14), here 3.14 is the parameter value. We know that without a value like 3.14, the sin() function will have no value to perform the sine operations on. Similarly, you can also specify, that your user-defined function expects some parameter for successful execution, while defining the function.

接下来,在圆括号内输入参数 。 这些是用户可以输入的一些必需值,并且在操作过程中在函数内部使用。 您可能还记得,在调用数学函数(例如sin(3.14) ,我们过去常常放几个数字,这里的3.14是参数值。 我们知道,没有像3.14这样的值, sin()函数将没有任何值来执行正弦运算。 同样,您也可以在定义函数时指定用户定义的函数期望成功执行某些参数。

Coming to the second line, we have the logic/algorithm statements. Here, we will be utilising all the parameters(if, any) to achieve what the function is supposed to do. We can have various operations, loops, conditional statements, etc. here to accomplish it. Taking the example of the add() function, where in simple addition is performed - a + b and the result is stored into some variable, let's say c, hence inside the add() function, we have an expression, c = a + b, a and b are the input values.

进入第二行,我们有逻辑/算法语句 。 在这里,我们将利用所有参数(如果有的话)来实现该功能应该执行的操作。 我们可以在这里进行各种操作,循环,条件语句等来完成它。 以add()函数为例,其中执行简单的加法-a a + b并将结果存储到某个变量中,例如c ,因此在add()函数内部,我们有一个表达式c = a + bab是输入值。

Finally, comes the return statement. Now the first thing to know about the return statement is that it is not mandatory to have it in a function. If your function is supposed to return a value after any operation, then you must use the return statement to output that value, else your function does not need it. Hence, you must always know when to have a return statement. The data returned can be anything - a number, string, a Boolean value, a list or anything else.

最后是return语句。 现在,关于return语句的第一件事是,将其包含在函数中不是强制性的。 如果您的函数应该在执行任何操作后返回一个值,则必须使用return语句输出该值,否则您的函数将不需要它。 因此,您必须始终知道何时需要return语句。 返回的数据可以是任何东西- 数字字符串布尔值, 列表或其他任何东西。

In case of the function add(), do we expect it to give us some (data) value? Yes. And What is it? The result of addition of the two numbers that are passed as parameters. So, add() function should have a return statement. To return any value, we just have to mention the value which we want to return, next to the return keyword.

如果使用add()函数,我们是否期望它给我们一些(数据)值? 是的 。 还有,这是什么? 作为参数传递的两个数字相加的结果 。 因此, add()函数应具有return语句。 要返回任何值,我们只需要在return关键字旁边提及要返回的值。

def add(a, b):
    c = (a+b)
    return c

Alternatively, you could have simply returned (a+b) directly, without storing it to some other variable too.

或者,您可以直接直接返回(a + b) ,而不必将其存储到其他变量中。

def add(a, b):
    return (a+b)

Once a function is defined, we can use it by simply calling it as we do for the built-in function i.e., if we want to add 5 and 9, then,

定义函数后,我们可以像调用内置函数一样通过简单地调用它来使用它,即,如果我们想 59 相加

>>> print add(5, 9)

14

14

In fact, you can even pass a function as a parameter! For example:

实际上,您甚至可以将函数作为参数传递! 例如:

>>> print add(5, add(7, 6))

18

18

Confused? Don't worry, let us explain. First, add(7, 6) will be evaluated and its result, i.e., 13 will be passed inside the second add() function as a parameter, to be added with 5. Therefore, the final result will be the output of, add(5, 13), which is 18.

困惑? 不用担心,让我们解释一下。 首先,将评估add(7, 6)并将其结果(即13 add()作为参数传递给第二个add()函数,并与5相加。 因此,最终结果将是add(5, 13)的输出,即18

函数的返回类型 (Return Type of a function)

Every function has a return-type, which is nothing but the type of value it returns. It's very simple to decide what is the return-type of any function. In add() function, if a and b are integer, then add() function will return an integer value, which will be it's return-type. Similarly, if the function is returning a list, then it's return-type will be a list. For built-in functions, you can find the return-type of every function specified in the official documentation.

每个函数都有一个return-type ,它只是返回值的类型。 确定任何函数的返回类型是非常简单的。 在add()函数中,如果abinteger ,则add()函数将返回一个数值,该值将是它的return-type 。 同样,如果函数正在返回列表 ,则它的return-type将是list 。 对于内置函数,可以找到官方文档中指定的每个函数的返回类型

But how can every function have a return-type, because we mentioned earlier, that having a return statement is completely optional and it totally depends on whether you need it or not in the function. Hence, the question arises, that what will be the return type of the functions which doesn't return anything? The answer is, void, which is pretty much synonymous to empty or nothing, stating that if there is no return statement then the function will have void return type.

但是,每个函数如何才能具有return-type ,正如我们前面提到的那样,具有return语句是完全可选的,并且它完全取决于您是否需要该函数。 因此,出现一个问题,什么是不返回任何内容的函数的返回类型? 答案是void ,它几乎等同于emptynone ,它表示如果没有return语句,则该函数将具有void返回类型。

Let's see where we can use the functions with return-type void.

让我们看看在哪里可以使用带有return型void的函数。

Hint: As they do not return anything, these can be used to break your program into smaller units.

提示:由于它们不返回任何内容,因此可以将它们分解为较小的程序。

Suppose there is a simple program, wherein, you take a positive number as input from the user and print all the even numbers and double of all the odd numbers, starting from 1 to that number. A program without any function will look like following:

假设有一个简单的程序,其中,您从用户处取一个正数作为输入,并打印从1到该数字的所有偶数和所有奇数的双数。 没有任何功能的程序如下所示:

n = input()
for i in xrange(1, n+1):
	if i%2 == 0:
		print i
	else:
		print 2*i

Now let's try to achieve this with a function. We will start by defining the function on the top. Although, it doesn't matter where you define the function because that has no effect on the flow of execution. Only calling a function will begin the execution of the function. But it's a good practice to define all the functions at the starting of your program because that's where all the programmers look for all the user-defined functions when they are reviewing any code.

现在,让我们尝试通过一个函数来实现这一点。 我们将从在顶部定义函数开始。 虽然,在哪里定义函数并不重要,因为这对执行流程没有影响。 仅调用函数将开始执行该函数。 但是,在程序启动时定义所有功能是一个好习惯,因为这是所有程序员在检查任何代码时都在寻找所有用户定义功能的地方。

def check(k):
	if (k%2==0):
		print k
	else:
		print 2*k

n = input()
for i in xrange(1, i+1):
	check(i)

As you can see we just picked up the logic of checking whether the number is even or not and defined it inside the check() function. And then we call it in the for loop, passing a new value to it in every iteration. This actually cleaned up the for loop a bit and made it look tidier.

如您所见,我们只是了解了检查数字是否为偶数的逻辑,并在check()函数中对其进行了定义。 然后我们在for循环中调用它,在每次迭代中将新值传递给它。 这实际上清理了for循环,并使它看起来更整洁。

The above program is a simple program, but when you will write programs with 100s of lines of code, then divinding the program into functions is a very good practice.

上面的程序是一个简单的程序,但是当您编写包含数百行代码的程序时,将程序划分为函数是一个很好的做法。

One advantage of using a function is that you can re-use that function anytime, by simply calling it. In the example above, if we want to print a number if it's even, or print the double of it, if it's odd, then all we have to do is simply call the function, and pass that number as the argument, and it's done. check(9), Handy, right?

使用函数的一个优点是您可以随时通过简单地调用它来重用该函数。 在上面的示例中,如果我们想打印一个偶数,或者打印一个双数,如果它是奇数,那么我们要做的就是简单地调用该函数,并将该数字作为参数传递,就可以了。 check(9) ,方便吗?

默认参数 (Default Arguments)

Default arguments are used when you need to pre-set the value for the parameters. That is, if in the future we don't pass any variable as an argument while calling the function, then the function will assume the default value to execute its statements.

当您需要预设参数值时,将使用默认参数。 也就是说,如果将来在调用函数时不传递任何变量作为参数,则该函数将采用默认值来执行其语句。

Now, how to define the default arguments? Let's take the example of add() function. What should happen if we do this:

现在,如何定义默认参数? 让我们以add()函数为例。 如果执行此操作会发生什么:

>>> print add()

Without any default parameter, python will throw an error straight away. So let's set the default arguments for the add() function, so that it works, even without argument values. We think the defulat values should be zero. With this, the returned value will be 0 + 0, i.e. 0, which makes sense too since we haven't passed any parameter/argument value.

没有任何默认参数,python将立即引发错误。 因此,让我们为add()函数设置默认参数,以便即使没有参数值也可以使用。 我们认为最小化值应为零。 这样,返回值将是0 + 0 ,即0 ,这也很有意义,因为我们没有传递任何参数/参数值。

The updated add() function will be,

更新后的add()函数将是

def add(a=0, b=0):
    return (a+b)

And it's done.

完成了。

>>> print add(10, 6)
>>> print add()

16 0

16 0

别名功能名称 (Aliasing function names)

Python has a special feature where you can create an alias of any function, i.e. if you think a function name is too long and not worth typing every time, you can decide a new name for it, without altering the original function. Taking the example of add() function, suppose we want a shorter or different name for this function, but without editing the original function, we can do so by using the function aliasing feature. Suppose we want to rename add() to a(), then,

Python具有一项特殊功能,您可以在其中创建任何函数的别名,即,如果您认为函数名太长且不值得每次键入,则可以为它确定一个新名称,而无需更改原始函数。 以add()函数为例,假设我们想为该函数使用更短或不同的名称,但是无需编辑原始函数,我们可以使用函数别名功能来做到这一点。 假设我们想将add()重命名为a() ,那么,

>>> a = add

And done. After this line, add() and a() would call the same function, thus, obviously, the parameters need to be same too. Hence now the following will work just like add() function,

并做了。 在此行之后, add()a()将调用相同的函数,因此,显然,参数也必须相同。 因此,下面的代码将像add()函数一样工作,

>>> print a(9, 8)

17

17

翻译自: https://www.studytonight.com/python/functions-in-python

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值