于 2020 年 1 月 7 日更新
函数是可重用的代码段,可帮助我们组织代码的结构。 我们创建函数,以便我们可以在程序中多次运行一组语句,而无需重复自己。
创建函数
Python 使用def关键字启动函数,以下是语法:
def function_name(arg1, arg2, arg3, .... argN):#statement inside function
注意:
函数内的所有语句均应使用相等的空格缩进。 函数可以接受零个或多个括在括号中的参数(也称为参数)。 您也可以使用pass关键字来省略函数的主体,如下所示:
def myfunc():pass
让我们来看一个例子。
def sum(start, end):result = 0for i in range(start, end + 1):result += iprint(result)sum(10, 50)
预期输出:
1230
上面我们定义了一个名为sum()的函数,它具有两个参数start和end。 该函数计算从start到end开始的所有数字的总和。
具有返回值的函数。
上面的函数只是将结果打印到控制台,如果我们想将结果分配给变量以进行进一步处理怎么办? 然后,我们需要使用return语句。 return语句将结果发送回调用方并退出该函数。
def sum(start, end):result = 0for i in range(start, end + 1):result += ireturn results = sum(10, 50)print(s)
预期输出:
1230
在这里,我们使用return语句返回数字总和并将其分配给变量s。
您也可以使用return陈述式而没有返回值。
def sum(start, end):if(start > end):print("start should be less than end")return # here we are not returning any value so a special value None is returnedresult = 0for i in range(start, end + 1):result += ireturn results = sum(110, 50)print(s)
预期输出:
start should be less than endNone
在 python 中,如果您未从函数显式返回值,则始终会返回特殊值None。 让我们举个例子:
def test(): # test function with only one statementi = 100print(test())
预期输出:
None
如您所见,test()函数没有显式返回任何值,因此返回了None。
全局变量与局部变量
全局变量:未绑定到任何函数但可以在函数内部和外部访问的变量称为全局变量。
局部变量:在函数内部声明的变量称为局部变量。
让我们看一些例子来说明这一点。
示例 1 :
global_var = 12 # a global variabledef func():local_var = 100 # this is local variableprint(global_var) # you can access global variables in side functionfunc() # calling function func()#print(local_var) # you can't access local_var outside the function, because as soon as function ends local_var is destroyed
预期输出:
12
示例 2:
xy = 100def cool():xy = 200 # xy inside the function is totally different from xy outside the functionprint(xy) # this will print local xy variable i.e 200cool()print(xy) # this will print global xy variable i.e 100
预期输出:
200100
您可以使用global关键字后跟逗号分隔的变量名称(,)在全局范围内绑定局部变量。
t = 1def increment():global t # now t inside the function is same as t outside the functiont = t + 1print(t) # Displays 2increment()print(t) # Displays 2
预期输出:
22
请注意,在全局声明变量时不能为变量赋值。
t = 1def increment():#global t = 1 # this is errorglobal tt = 100 # this is okayt = t + 1print(t) # Displays 101increment()print(t) # Displays 101
预期输出:
101101
实际上,无需在函数外部声明全局变量。 您可以在函数内部全局声明它们。
def foo():global x # x is declared as global so it is available outside the functionx = 100foo()print(x)
预期输出: 100
具有默认值的参数
要指定参数的默认值,您只需要使用赋值运算符分配一个值。
def func(i, j = 100):print(i, j)
以上函数具有两个参数i和j。 参数j的默认值为100,这意味着我们可以在调用函数时忽略j的值。
func(2) # here no value is passed to j, so default value will be used
预期输出:
2 100
再次调用func()函数,但这一次为j参数提供一个值。
func(2, 300) # here 300 is passed as a value of j, so default value will not be used
预期输出:
2 300
关键字参数
有两种方法可以将参数传递给方法:位置参数和关键字参数。 在上一节中,我们已经看到了位置参数的工作方式。 在本节中,我们将学习关键字参数。
关键字参数允许您使用像name=value这样的名称值对来传递每个参数。 让我们举个例子:
def named_args(name, greeting):print(greeting + " " + name )
named_args(name='jim', greeting='Hello')named_args(greeting='Hello', name='jim') # you can pass arguments this way too
期望值:
Hello jimHello jim
混合位置和关键字参数
可以混合使用位置参数和关键字参数,但是对于此位置参数必须出现在任何关键字参数之前。 我们来看一个例子。
def my_func(a, b, c):print(a, b, c)
您可以通过以下方式调用上述函数。
# using positional arguments onlymy_func(12, 13, 14)# here first argument is passed as positional arguments while other two as keyword argumentmy_func(12, b=13, c=14)# same as abovemy_func(12, c=13, b=14)# this is wrong as positional argument must appear before any keyword argument# my_func(12, b=13, 14)
预期输出:
12 13 1412 13 1412 14 13
从函数返回多个值
我们可以使用return语句从函数中返回多个值,方法是用逗号(,)分隔它们。 多个值作为元组返回。
def bigger(a, b):if a > b:return a, belse:return b, as = bigger(12, 100)print(s)print(type(s))
预期输出:
(100, 12)<class 'tuple'>
在下一篇文章中,我们将学习 Python 循环
