Python Basics - Functions

function

definition

We know that the program is executed in order, then we will encounter a problem of code listing during development. If we can extract part of the code that implements the functions according to our wishes, it will be as simple as one line or a few when using it. OK?
So functions come into being.
Functions are organized, reusable pieces of code that implement a single, or related, function.

function definition rules
  1. starts with the keyword def followed by the function name, again parentheses,
  2. Parameters can be placed in parentheses or not
  3. Function content must start with a colon and be indented
  4. At the end of the function, return can be followed by an expression, or not
  5. In the first line of the function, you can optionally write function comments as needed
def functionname( parameters ):
   "函数注释,可有可无"
   function_suite
   return [expression]
parameter
Required parameters

The so-called necessary parameters means that when the defined function requires parameters, it must be passed in when calling, otherwise an error will be reported.
For example :

#定义函数
def printStr(str):
    'this is some discribe'
    print str
    return

#调用函数
'''如果这样调用 printStr(),那么会报错,必须这样调用 printStr('helle word')
这里的'hello word' 就是必备参数'''
keyword arguments

We may feel confused when we hear this name, so let's take an example:

#可写函数说明
def printinfo( name, age ):
   print "aame: ", name;
   print "age ", age;
   return;
 #调用printinfo函数
printinfo( age=18, name="Rocky" );

In the example, we can find that when the function is called, the parameters we pass in are not in the same order as the defined parameters. Don't worry, no error will be reported, because Python handles it for us, and the final result is still correct. The reason is that when the parameters are passed , is 'assigned' according to the parameter name (keyword) reserved by the definition function, then when the parameter is used, the value will be correctly found according to the variable name

default parameters

Default parameters are also called default parameters. When calling a function, if no parameters are passed in, the function will use the default value for operation.


def printinfo( name, age = 18 ):
   print "aame: ", name;
   print "age ", age;
   return;
#调用printinfo函数
printinfo( name="Rocky" );

For example, in the above example, according to the normal requirements, we need to pass in two values. Now only one value is passed in, and it runs through!
If you look closely, you will find that the function defined this time is different from the original one. The age here is directly assigned. The function defined in this form is the default parameter function. The
characteristic is that it will be used by default when no default parameters are passed in. Reserved parameter value, if passed in, it will not be overwritten, use the passed in value

variable length parameter

Indefinite-length parameters, as the name suggests, is that when defining a function, the number of reserved parameters is not fixed. In theory, you can pass in as many as you want. This is similar to the variable parameters in java,
but it java. Inconsistent method definitions for
indefinite Parameter function definition format:

def functionname([formal_args,] *var_args_tuple ):
   function_suite
   return [expression]

illustrate:

  1. The parameter characteristics here are one more than the previous one*
  2. The variable name marked with * here will store all unnamed variable parameters

Specific use examples:

# 可写函数说明
def printinfo( arg1, *vartuple ):
   print arg1
   for var in vartuple:
      print var
   return;

# 调用printinfo 函数
printinfo( 10 );#结果是 10
printinfo( 70, 60, 50 ); #结果是 70,60,50
anonymous function

The so-called anonymous function is that we cannot see the name of the function, and its creation needs to pass the lambda function

lambda function features

  1. it's just an expression
  2. Because its body is an expression, only limited logic can be encapsulated when creating an anonymous function
  3. It has its own namespace and cannot access parameters other than its own parameters
  4. it's only one line

Format:

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

An example of an anonymous function:

# 可写函数说明
sum = lambda arg1, arg2: arg1 + arg2;

# 调用sum函数
print "相加后的值为 : ", sum( 10, 20 ) #结果30
print "相加后的值为 : ", sum( 20, 20 ) #结果 40
Some notes on variables

A variable, as the name suggests, is a variable quantity
such as a = 1, a = 'hello', etc. where a is a variable

The use of variables has a scope, which we call the scope.
According to the scope, variables are divided into global variables and local variables.

local variable

The scope of a variable defined inside a function is only inside the function and belongs to the local scope, so such a variable is a local variable. In general, a local variable can only be accessed and used inside the function, but a local variable is added in front of it when it is defined. global can be turned into a global variable for use.
For example :

Money = 2000
def AddMoney():
   global Money #表示是全局变量
   #以下语句会先使用Money 在方法内部有找不到因此会报错,虽然在全局中找到了Money,但是下语句是修改全局变量,除非用 global 修饰 否则一定报错
   Money = Money + 1
print Money
AddMoney()
print Money
这时候打印出来的结果是2001
如果把  global Money注释掉 会报错:UnboundLocalError: local variable 'Money' referenced before assignment
这也就说明 函数外部的变量在内部如果不用global来标识一下直接使用会找不到局部变量
global variable

Contrary to local variables, its scope is wider, and global definitions are available everywhere

deep copy

A copy, as the name suggests, is a copy of one. There is such a scenario in our program:
I have created a variable b = 2, and then passed in a custom function to add 1 to b and return to print. The result is whether the internal printing of the function is 3, and the external printing is still 2.

def addOne( b ):
    b = b+1
    print b
    return

b = 2
addOne(b) #结果为3
print b # 结果为2

Here we are vague. Why did it not change after adding one inside the function?

Two concepts are introduced here: mutable objects and immutable objects

  1. Immutable objects
    In python, strings, tuples, and numbers are immutable objects. The so-called change is even reassignment, and reassignment is to reallocate memory and create a new object
  2. Variable objects
    In python, list, dict, etc. are objects that can be modified. Note that the modification here is the element, and the memory address of the object has not changed. You can use id (object) to check before and after

In the above example, the parameters of addOne can be named arbitrarily, and we can give him a, etc.
Then we analyze the process of executing the above function call

  1. First of all, we addOne(b) this is the call, the value of b is 2.
    This process is actually assigning the value of the external variable 2 to our formal parameter b. At this time, the system recreates an object with Variables can have arbitrary names
  2. Inside the function, we add one to the variable. In fact, the step is that the value of b+1 is re-given to b. At this time, b is equivalent to a new local variable.
  3. Then we print out that the value of the local variable is 3
  4. print the value of the global variable b as 2

Let me explain here: creating a new object is to re-allocate a memory address. In the above example, the function calls to create a new object twice in a row, which is completely different from the original b, and naturally the final value does not change.

shallow copy

Let's look at an example:

 a = [1, 2, 3]
 b = a
 b.append(5)
 print a, b 
结果是[1, 2, 3, 5] [1, 2, 3, 5]

In this way, we will find the problem. It is not right. I want to add 5 after b, and how to add a.
This is a shallow copy. Here, variables a and b both point to the same object (a list) , so, once you modify one of the two, the other will be affected. No matter what, the original object will be modified.
Then someone asks, even if I need to change one object, the other remains unchanged, so we can To introduce deep copy

deep copy

Let's look at another example:

import copy #这里是模块的使用,下节在讲述
a = [ ['a'], [1, 2], ['rocky', 21] ] #原始数据
copy_a = copy.deepcopy(a) #复制数据,注意是深拷贝
copy_a[1].append(3) #复制后的数据修改
print a, copy_a  #打印

结果:[['a'], [1, 2], ['rocky', 21]] [['a'], [1, 2, 3], ['rocky', 21]]

Finally, it is found that the original data a has not changed, but the copied data is changed, and the purpose is achieved. As for the principle, we need to see the underlying code, which will not be described here.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324909517&siteId=291194637