Function (1), function (

Source: Internet
Author: User
Tags variable scope

Function (1), function (

Define functions:

 

# Syntax def function name (parameter 1, parameter 2, parameter 3,...): '''comment ''' value returned by return of function body # function name must reflect its meaning

Process: A function with no return value

 

 

Function parameters:

  • Parameter: memory units are allocated only when called. The allocated memory units are immediately released at the end of the call. Therefore, the parameter is valid only within the function.
  • Real parameters: they can be constants, variables, expressions, functions, etc. When calling a function, you must have a definite value to pass these values to the form parameters.

 

 

Def test (x, y, z): # x = 1, y = 2, z = 3 print (x) print (y) print (z) # location parameter, one-to-one correspondence is required. test (1, 2, 3) # keyword parameters are not required for one-to-one correspondence. test (y = 1, x = 2, z = 3) # output result: 123213

 

 

# Parameter group: ** dictionary * List def test (x, * args, ** kwargs): print (x) print (args, args [-1]) print (kwargs, kwargs. get ('s') test (1, * [1, 2, 3], ** {'s': 1}) # output result: 1 (1, 2, 3) 3 {'s ': 1} 1

 

Global and local variables:

The variables defined in the subroutine are called local variables, and the variables defined at the beginning of the program are called global variables.

The global variable scope is the whole program, and the local variable scope is the subroutine that defines the variable. When a global variable has the same name as a local variable, the local variable takes effect in the subroutine that defines the local variable, and the global variable takes effect elsewhere.
Name = 'reese 'def change_name (): print ('My name', name) change_name () def change_name (): name = 'shuai 'print ('My name', name) change_name () print (name) def change_name (): global name = 'shuai 'print ('My name', name) change_name () print (name) # output result: my name is reese my name is handsome

# If the function does not have a global keyword, the system first reads the local variable and can read the global variable;

However, you can perform operations on internal elements for variable types (except numbers, strings, and ancestor.

# If a function contains a global keyword, the variable is essentially a global variable and can be read and assigned values.

# Generally, the global variable name is in upper case and the local variable name is in lower case.

 

Recursion
# Recursive call def calc (n): print (n) if int (n/2) = 0: return n s = calc (int (n/2 )) return scalc (10) # output: 10521

 

Recursive features:

1. There must be a clear termination condition

2. Each time you enter a deeper layer of recursion, the problem scale should be reduced compared to the previous recursion.

3. the recursion efficiency is not high. Too many recursive layers will cause stack overflow (in the computer, function calls are implemented through the stack data structure,

Every time a function is called, a stack frame is added to the stack, and every time the function is returned, the stack will be reduced by a stack frame. Because the stack size is not infinite, too many recursive calls will cause stack overflow)

 

# Question import timeperson_list = ['link', 'Chief officer ', 'queye', 'dante '] def ask_way (person_list): print ('-'* 60) if len (person_list) = 0: return 'Nobody knows' person = person_list.pop (0) if person = 'dante ': return' % s: I know, the road is under your feet, when I leave the path too long, I will know '% person print ('Hi male [% s], and dare to ask where the path is' % person) print ('% s: I don't know, but when you read your eye, you are waiting. I will help you to ask % s... '% (person, person_list) time. sleep (3) res = ask_way (person_list) # print ('% s: % res' % (person, res) return resres = ask_way (person_list) print (res)

 

Function Scope

 

The scope is fixed when the function is defined and will not change as the call location changes.

Name = "reese" def s (): name = "neo" def n (): print (name) return nfunc = s () func () # output: neo

 

Anonymous functions:

The specified function does not need to be displayed.

Def calc (x): return x + 10res = calc (10) print (res) # output: 20 # Use the anonymous function: func = lambda x: x + 10 print (func (10) # output: 20

 

Func = lambda x, y, z: x + y + zprint (func (1, 2, 3) # output: 6

 

 

Map function:

 

Num = [3, 4, 5, 6, 11, 7, 54] # lambda x: x + 1def add_one (x ): # list element auto increment return x + 1 # lambda x: x-1def minus_one (x): # list element auto increment return x-1def map_test (func, array ): ret = [] for I in num: res = func (I) ret. append (res) return retprint (map_test (add_one, num) # print (map_test (lambda x: x + 1, num) # available anonymous function print (map_test (minus_one, num) # print (map_test (lambda x: X-1, num) # ultimate version def map_test (func, array): ret = [] for I in array: res = func (I) ret. append (res) return retprint (map_test (lambda x: x + 1, num) # output result: [4, 5, 6, 7, 12, 8, 55] [2, 3, 4, 5, 10, 6, 53] [4, 5, 6, 7, 12, 8, 55]

 

Map:

Process each element in the sequence. The result is a list with the same number and position as the original one.

Num = [3, 4, 5, 6, 11, 7, 54] res = map (lambda x: x + 1, num) print ('built-in function map, processing result ', list (res) print (list (map (minus_one, num) msg = "reese" print (list (map (lambda x: x. upper (), msg) # output result: the built-in Function map, processing result [4, 5, 6, 7, 12, 8, 55] [2, 3, 4, 5, 10, 6, 53] ['R', 'E', 'E', 's', 'E']

 

Filter function:

Each element in the convenience sequence is judged to obtain a Boolean value for each element. If it is True, it is left behind

People = ['reese ', 'neo _ s', 'link'] print (filter (lambda n: not n. endswith ('s '), people) res = filter (lambda n: not n. endswith ('s '), people) print (list (res) print (list (filter (lambda n: not n. endswith ('s'), people) # output: <filter object at 0x04E612B0> ['reese ', 'link'] ['reese', 'link']

 

 

Reduce function:

Process a sequence and merge the sequence.

# Reduce function from functools import performancenum = [1, 2, 3, 4, 5] print (reduce (lambda x, y: x + y, num,) # output: 15

 

Built-in functions:

 

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.