Python introductory tutorial | Python functions and parameters

Function introduction

Functions are organized, reusable code segments used to implement a single or related function.

Functions can improve application modularity and code reuse. You already know that Python provides many built-in functions, such as print(). But you can also create your own functions, which are called user-defined functions.

define a function

You can define a function with the functionality you want, here are the simple rules:

  • A function code block begins with the def keyword, followed by the function identifier name and parentheses ().
  • Any incoming parameters and independent variables must be placed between parentheses, and the parentheses can be used to define parameters.
  • The first line of a function can optionally use a docstring - used to store the function description.
  • Function content starts with a colon: and is indented.
  • return [expression] ends the function and optionally returns a value to the caller. Return without expression is equivalent to returning None.
    Insert image description here

function syntax

Python uses the def keyword to define functions. The general format is as follows:

def function name (parameter list):
function body

By default, parameter values ​​and parameter names are matched in the order defined in the function declaration.
Example
Let's use a function to print "Hello World!":
interactive mode


>>> def hello() :
...     print("Hello World!")
...
>>> hello()
Hello World!
>>>

For more complex applications, bring parameter variables to the function:
compare two numbers and return the larger number:
script mode

def max(a, b):
    if a > b:
        return a
    else:
        return b
 
a = 4
b = 5
print(max(a, b))

The output of the above example is:

5

Calculate Area Function:
Script Mode

# 计算面积函数
def area(width, height):
    return width * height
 
def print_welcome(name):
    print("Welcome", name)
 
print_welcome("Tarzan")
w = 4
h = 5
print("width =", w, " height =", h, " area =", area(w, h))

The output of the above example is:

Welcome Tarzan
width = 4 height = 5 area = 20

function call

Define a function: Give the function a name, specify the parameters contained in the function, and the code block structure.

Once the basic structure of this function is complete, you can execute it through another function call or directly from the Python command prompt.

The following example calls the printme() function:

# 定义函数
def printme( str ):
   # 打印任何传入的字符串
   print (str)
   return
 
# 调用函数
printme("我要调用用户自定义函数!")
printme("再次调用同一函数")

The output of the above example is:

I want to call a user-defined function!
Call the same function again

parameter

The following are the formal parameter types that can be used when calling functions:

  • Required parameters
  • keyword arguments
  • Default parameters
  • variable length parameters

Required parameters

Required parameters must be passed into the function in the correct order. The quantity when called must be the same as when declared.

When calling the printme() function, you must pass in a parameter, otherwise a syntax error will occur:

#可写函数说明
def printme( str ):
   "打印任何传入的字符串"
   print (str)
   return
 
# 调用 printme 函数,不加参数会报错
printme()

The output of the above example is:

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\test.py", line 7, in <module>
    printme()
TypeError: printme() missing 1 required positional argument: 'str'

keyword arguments

Keyword parameters are closely related to function calls. Function calls use keyword parameters to determine the values ​​of the parameters passed in.

Using keyword arguments allows a function to be called in an order in which the arguments are not declared, because the Python interpreter can match argument names to argument values.

The following example uses parameter names when calling function printme() :

#可写函数说明
def printme( str ):
   "打印任何传入的字符串"
   print (str)
   return
 
#调用printme函数
printme( str = "泰山技术博客")

The output of the above example is:

Taishan Technology Blog

The following example demonstrates the use of function parameters without specifying the order:

#可写函数说明
def printinfo( name, age ):
   "打印任何传入的字符串"
   print ("名字: ", name)
   print ("年龄: ", age)
   return
 
#调用printinfo函数
printinfo( age=30, name="tarzan" )

The output of the above example is:

Name: tarzanAge
: 30

Default parameters

When calling a function, if no parameters are passed, default parameters are used. In the following examples, if the age parameter is not passed in, the default value is used:

#可写函数说明
def printinfo( name, age = 30 ):
   "打印任何传入的字符串"
   print ("名字: ", name)
   print ("年龄: ", age)
   return
 
#调用printinfo函数
printinfo( age=50, name="tarzan" )
printinfo( name="tarzan" )

Name: tarzan
Age: 50
Name: tarzan
Age: 30

variable length parameters

You may need a function that can handle more arguments than when declared. These parameters are called variable-length parameters, and unlike the above two parameters, they are not named when declared. The basic syntax is as follows:

def functionname([formal_args,] *var_args_tuple ):
   "函数_文档字符串"
   function_suite
   return [expression]

Parameters with an asterisk * will be imported in the form of tuples to store all unnamed variable parameters.

# 可写函数说明
def printinfo( arg1, *vartuple ):
   "打印任何传入的参数"
   print ("输出: ")
   print (arg1)
   print (vartuple)
 
# 调用printinfo 函数
printinfo( 70, 60, 50 )

The output of the above example is:

Output:
70
(60, 50)

If no parameters are specified when the function is called, it is an empty tuple. We can also not pass unnamed variables to the function. Examples below:

# 可写函数说明
def printinfo( arg1, *vartuple ):
   "打印任何传入的参数"
   print ("输出: ")
   print (arg1)
   for var in vartuple:
      print (var)
   return
 
# 调用printinfo 函数
printinfo( 10 )

The output of the above example is:

Output:
10

There is also a parameter with two asterisks plus an asterisk * * The basic syntax is as follows:

def functionname([formal_args,] **var_args_dict ):
   "函数_文档字符串"
   function_suite
   return [expression]

Parameters with two asterisks * * will be imported in the form of a dictionary.

# 可写函数说明
def printinfo( arg1, **vardict ):
   "打印任何传入的参数"
   print ("输出: ")
   print (arg1)
   print (vardict)
 
# 调用printinfo 函数
printinfo(1, a=2,b=3)

The output of the above example is:

Output:
1
{'a': 2, 'b': 3}

When declaring a function, the asterisk * can appear alone in the parameters, for example:

def f(a,b,*,c):
    return a+b+c

If the asterisk * appears alone , the parameters after the asterisk * must be passed in with the keyword:
interactive mode

>>> def f(a,b,*,c):
...     return a+b+c
...
>>> f(1,2,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() takes 2 positional arguments but 3 were given
>>> f(1,2,c=3)
6
>>>

Mandatory positional parameters

Python3.8 adds a new function parameter syntax / to indicate that function parameters must use specified positional parameters and cannot use keyword parameters.

In the following example, formal parameters a and b must use specified positional parameters, c or d can be positional parameters or keyword parameters, and e and f are required to be keyword parameters:

def f(a, b, /, c, d, *, e, f):
    print(a, b, c, d, e, f)

The following usage methods are correct:

f(10, 20, 30, d=40, e=50, f=60)

An error will occur when using the following methods:
interactive mode

>>> f(10, b=20, c=30, d=40, e=50, f=60)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() got some positional-only arguments passed as keyword arguments: 'b'
>>> f(10, 20, 30, 40, 50, f=60)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() takes 4 positional arguments but 5 positional arguments (and 1 keyword-only argument) were given
>>>

Parameter passing

In Python, types belong to objects. Objects have different types. Variables have no type:

#把列表赋值给a
a=[1,2,3]
#把字符串赋值给a
a="Tarzan"

In the above code, [1,2,3] is of List type, "Runoob" is of String type, and variable a has no type. It is just a reference to an object (a pointer), which can point to a List type object or Points to a String type object.

Mutable and immutable objects

In python, strings, tuples, and numbers are immutable objects, while list, dict, etc. are modifiable objects.

  • Immutable type: After assigning a=5 to a variable, assign a=10. Here, a new int value object 10 is actually generated, and a is pointed to it, while 5 is discarded. It does not change the value of a, which is equivalent to newly generating a. .

  • Variable type: variable assignment la=[1,2,3,4] and then assignment la[2]=5 changes the value of the third element of list la. La itself is not moved, only part of its internal value has been modified.

Parameter passing of python function:

  • Immutable types: C++-like value transfer, such as integers, strings, and tuples. For example, fun(a) only transfers the value of a and does not affect the a object itself. If the value of a is modified inside fun(a), a new object of a is generated.

  • Variable types: similar to C++ reference transfer, such as lists and dictionaries. For example, fun(la) will actually pass la. After modification, la outside fun will also be affected.

Everything in Python is an object. Strictly speaking, we cannot say whether to pass by value or by reference. We should say passing immutable objects and passing mutable objects.

Python passes immutable object instance

Use the id() function to view memory address changes:

def change(a):
    print(id(a), a, sep=' - ')   # 指向的是同一个对象
    a=10
    print(id(a), a, sep=' - ')  # 一个新对象
 
b=1
print(id(b), b, sep=' - ')
change(b)
print(id(b), b, sep=' - ')

The output result of the above example is:

140705853137704 - 1
140705853137704 - 1
140705853137992 - 10
140705853137704 - 1

You can see that before and after calling the function, the formal parameters and actual parameters point to the same object (the object id is the same). After modifying the formal parameters inside the function, the formal parameters point to different ids.

  • Formal parameters (Parameter) refer to the parameters declared when defining a function and are used to describe the parameters that the function needs to receive when executing. Formal parameters can be used inside a function or outside a function.
  • Actual parameters (Argument) refer to the parameters passed to the function when calling the function, and are used to specify the parameters that need to be used when the function is executed. Actual parameters can be constants, variables, expressions, etc.

In the above example, the formal parameter is a and the actual parameter is b .

Pass mutable object instance

If the variable object modifies the parameters in the function, then in the function that calls this function, the original parameters are also changed. For example:

# 可写函数说明
def changeme( mylist ):
   "修改传入的列表"
   mylist.append([1,2,3,4])
   print ("函数内取值: ", mylist)
   return
 
# 调用changeme函数
mylist = [10,20,30]
changeme( mylist )
print ("函数外取值: ", mylist)

The object passed into the function and the new content added at the end use the same reference. So the output is as follows:

Values ​​within the function: [10, 20, 30, [1, 2, 3, 4]]
Values ​​outside the function: [10, 20, 30, [1, 2, 3, 4]]

anonymous function

Python uses lambdas to create anonymous functions.

The so-called anonymous means that you no longer use the standard form of def statement to define a function.

Lambda is just an expression, and the function body is much simpler than def.
The body of a lambda is an expression, not a block of code. Only limited logic can be encapsulated in lambda expressions.
The lambda function has its own namespace and cannot access parameters outside its own parameter list or in the global namespace.
Although the lambda function seems to only be written in one line, it is not equivalent to the inline function of C or C++ . The purpose of the inline function is to call small functions without occupying stack memory, thus reducing the cost of function calls and improving the execution speed of the code.

Syntax
The syntax of the lambda function contains only one statement, as follows:

lambda [ arg1 [, arg2 ,...argn ]]: expression

Example : Set parameter a plus 10:

x = lambda a : a + 10
print(x(5))

The output of the above example is:

15

The following example anonymous function sets two parameters:

# 可写函数说明
sum = lambda arg1, arg2: arg1 + arg2
 
# 调用sum函数
print ("相加后的值为 : ", sum( 10, 20 ))
print ("相加后的值为 : ", sum( 20, 20 ))

The output of the above example is:

The added value is: 30The
added value is: 40

We can encapsulate anonymous functions in a function, so that we can use the same code to create multiple anonymous functions.
The following example encapsulates the anonymous function in the myfunc function and creates different anonymous functions by passing in different parameters:

def myfunc(n):
  return lambda a : a * n
 
mydoubler = myfunc(2)
mytripler = myfunc(3)
 
print(mydoubler(11))
print(mytripler(11))

The output of the above example is:

22
33

Guess you like

Origin blog.csdn.net/weixin_40986713/article/details/132829531