📜  Python用户定义函数

📅  最后修改于: 2022-05-13 01:54:31.974000             🧑  作者: Mango

Python用户定义函数

函数是一组接受输入、进行特定计算并产生输出的语句。这个想法是将一些常见或重复完成的任务放在一起并制作一个函数,这样我们就可以调用该函数,而不是为不同的输入一次又一次地编写相同的代码。
Python自带的函数称为内置函数。 Python提供了 print() 等内置函数,但我们也可以创建自己的函数。这些函数称为用户定义函数

用户定义函数

我们编写的所有函数都属于用户定义函数的范畴。以下是在Python中编写用户定义函数的步骤。

  • 在Python中,def 关键字用于声明用户定义的函数。
  • 缩进的语句块跟在函数名称和包含函数主体的参数之后。

句法:

def function_name():
    statements
    .
    .

例子:

Python3
# Python program to
# demonstrate functions
 
# Declaring a function
def fun():
    print("Inside function")
 
# Driver's code
# Calling function
fun()


Python3
# Python program to
# demonstrate functions
 
# A simple Python function to check
# whether x is even or odd
def evenOdd( x ):
    if (x % 2 == 0):
        print("even")
    else:
        print("odd")
   
# Driver code
evenOdd(2)
evenOdd(3)


Python3
# Python program to demonstrate
# default arguments
def myFun(x, y = 50):
    print("x: ", x)
    print("y: ", y)
   
# Driver code (We call myFun() with only
# argument)
myFun(10)


Python3
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname): 
     print(firstname, lastname) 
     
     
# Keyword arguments                  
student(firstname ='Geeks', lastname ='Practice')    
student(lastname ='Practice', firstname ='Geeks')


Python3
# Python program to illustrate  
# *args and **kwargs
def myFun1(*argv): 
    for arg in argv: 
        print (arg)
 
def myFun2(**kwargs): 
    for key, value in kwargs.items():
        print ("% s == % s" %(key, value))
   
# Driver code
print("Result of * args: ")
myFun1('Hello', 'Welcome', 'to', 'GeeksforGeeks')
 
print("\nResult of **kwargs")
myFun2(first ='Geeks', mid ='for', last ='Geeks')


Python3
# Python program to
# verify pass by reference
 
def myFun(x):
    print("Value received:", x, "id:", id(x))
 
# Driver's code
x = 12
print("Value passed:", x, "id:", id(x))
myFun(x)


Python3
def myFun(x, arr):
    print("Inside function")
 
    # changing integer will
    # Also change the reference
    # to the variable
    x += 10
    print("Value received", x, "Id", id(x))
 
    # Modifying mutable objects
    # will also be reflected outside
    # the function
    arr[0] = 0
    print("List received", arr, "Id", id(arr))
 
# Driver's code
x = 10
arr = [1, 2, 3]
 
print("Before calling function")
print("Value passed", x, "Id", id(x))
print("Array passed", arr, "Id", id(arr))
print()
 
myFun(x, arr)
 
print("\nAfter calling function")
print("Value passed", x, "Id", id(x))
print("Array passed", arr, "Id", id(arr))


Python3
# Python program to
# demonstrate return statement
  
def add(a, b):
  
    # returning sum of a and b
    return a + b
  
def is_true(a):
  
    # returning boolean of a
    return bool(a)
  
# calling function
res = add(2, 3)
print("Result of add function is {}".format(res))
  
res = is_true(2<5)
print("\nResult of is_true function is {}".format(res))


输出:

Inside function

参数化函数

该函数可以在左括号和右括号内将参数(也称为参数)作为输入,紧跟在函数名称之后,后跟一个冒号。
句法:

def function_name(argument1, argument2, ...):
    statements
    .
    .

例子:

Python3

# Python program to
# demonstrate functions
 
# A simple Python function to check
# whether x is even or odd
def evenOdd( x ):
    if (x % 2 == 0):
        print("even")
    else:
        print("odd")
   
# Driver code
evenOdd(2)
evenOdd(3)

输出:

even
odd

默认参数

默认参数是一个参数,如果在该参数的函数调用中未提供值,则该参数采用默认值。以下示例说明了默认参数。
例子:

Python3

# Python program to demonstrate
# default arguments
def myFun(x, y = 50):
    print("x: ", x)
    print("y: ", y)
   
# Driver code (We call myFun() with only
# argument)
myFun(10)

输出:

x:  10
y:  50

注意:要了解有关默认参数的更多信息,请单击此处。

关键字参数

这个想法是允许调用者使用值指定参数名称,以便调用者不需要记住参数的顺序。
例子:

Python3

# Python program to demonstrate Keyword Arguments
def student(firstname, lastname): 
     print(firstname, lastname) 
     
     
# Keyword arguments                  
student(firstname ='Geeks', lastname ='Practice')    
student(lastname ='Practice', firstname ='Geeks')

输出:

Geeks Practice
Geeks Practice

可变长度参数

我们可以同时拥有普通和关键字可变数量的参数。

  • Python中函数定义中的特殊语法 *args 用于将可变数量的参数传递给函数。它用于传递非关键字、可变长度的参数列表。
  • Python函数定义中的特殊语法 **kwargs 用于传递带关键字的可变长度参数列表。我们使用带有双星的名称 kwargs。原因是双星允许我们传递关键字参数(以及任意数量的参数)。

例子:

Python3

# Python program to illustrate  
# *args and **kwargs
def myFun1(*argv): 
    for arg in argv: 
        print (arg)
 
def myFun2(**kwargs): 
    for key, value in kwargs.items():
        print ("% s == % s" %(key, value))
   
# Driver code
print("Result of * args: ")
myFun1('Hello', 'Welcome', 'to', 'GeeksforGeeks')
 
print("\nResult of **kwargs")
myFun2(first ='Geeks', mid ='for', last ='Geeks') 

输出:

Result of *args: 
Hello
Welcome
to
GeeksforGeeks

Result of **kwargs
mid == for
first == Geeks
last == Geeks

注意:要了解有关可变长度参数的更多信息,请单击此处。

通过引用传递还是按值传递?

需要注意的重要一点是,在Python中,每个变量名都是一个引用。当我们将变量传递给函数时,会创建对该对象的新引用。 Python中的参数传递与Java中的引用传递相同。为了确认这个 Python 的内置 id()函数在下面的例子中被使用。
例子:

Python3

# Python program to
# verify pass by reference
 
def myFun(x):
    print("Value received:", x, "id:", id(x))
 
# Driver's code
x = 12
print("Value passed:", x, "id:", id(x))
myFun(x)
输出
Value passed: 12 id: 11094656
Value received: 12 id: 11094656

输出:

Value passed: 12 id: 10853984
Value received: 12 id: 10853984

如果上述变量的值在函数内部发生变化,那么它将创建一个不同的变量作为不可变的数字。但是,如果在函数内部修改了可变列表对象,则更改也会反映在函数外部。
例子:

Python3

def myFun(x, arr):
    print("Inside function")
 
    # changing integer will
    # Also change the reference
    # to the variable
    x += 10
    print("Value received", x, "Id", id(x))
 
    # Modifying mutable objects
    # will also be reflected outside
    # the function
    arr[0] = 0
    print("List received", arr, "Id", id(arr))
 
# Driver's code
x = 10
arr = [1, 2, 3]
 
print("Before calling function")
print("Value passed", x, "Id", id(x))
print("Array passed", arr, "Id", id(arr))
print()
 
myFun(x, arr)
 
print("\nAfter calling function")
print("Value passed", x, "Id", id(x))
print("Array passed", arr, "Id", id(arr))

输出:

Before calling function
Value passed 10 Id 10853920
Array passed [1, 2, 3] Id 139773681420488

Inside function
Value received 20 Id 10854240
List received [0, 2, 3] Id 139773681420488

After calling function
Value passed 10 Id 10853920
Array passed [0, 2, 3] Id 139773681420488

有返回值的函数

有时我们可能需要函数的结果用于进一步的处理。因此,函数在完成执行时也应该返回一个值。这可以通过 return 语句来实现。
return 语句用于结束函数调用的执行并将结果(return 关键字后面的表达式的值)“返回”给调用者。 return 语句之后的语句不被执行。如果 return 语句没有任何表达式,则返回特殊值 None。
句法:

def fun():
    statements
    .
    .
    return [expression]

例子:

Python3

# Python program to
# demonstrate return statement
  
def add(a, b):
  
    # returning sum of a and b
    return a + b
  
def is_true(a):
  
    # returning boolean of a
    return bool(a)
  
# calling function
res = add(2, 3)
print("Result of add function is {}".format(res))
  
res = is_true(2<5)
print("\nResult of is_true function is {}".format(res))

输出:

Result of add function is 5

Result of is_true function is True