python05-namespaces/scopes/recursion

Source: Internet
Author: User

First, namespace and scope

1. Namespaces

Where the name is stored, there are three types of namespaces (previously left x=1,1 stored in memory, where does the name x reside?). Namespaces are where the name X and 1 bindings are stored)

2. Loading order of namespaces

Python test.py
#1, the Python interpreter starts first, so it first loads: built-in namespaces
#2, execute the test.py file, and then load the global namespace on file basis
#3, if a function is called during the execution of a file, the local namespace is generated temporarily

3. Search Order of Names

Local namespace---> Global namespaces---> built-in namespaces

#需要注意的是: In the global cannot view local, in the local can view the global, the following example
# max=1
# def F1 ():
# max=2
# def F2 ():
# max=3
# Print (max)
# F2 ()
# f1 () #打印3
# print (max) #打印1

4. Scope
#作用域即范围
-Global scope (the built-in namespace and the global namespace belong to this scope): Global survival, globally valid
-Local scope (local namespace belongs to this range): temporary survival, partially valid

# # #全局变量

A variable defined at the beginning of a program, scoped to the entire program

# NAME = "Product Manager"
# def Yangjian ():
# print (' I'm going to do ', NAME)

# print (' I'm going to do ', NAME)

# Yangjian ()

# # #局部变量

A variable defined in a subroutine, scoped to a subroutine that defines the variable

# def Qupengfei ():
# NAME = "Base"
# print (' I'm going to do ', NAME)

# Qupengfei ()

Second, global and nonlocal

1.global keywords

The ability to declare a variable inside a subroutine as a global variable, as in the following example:

# If there is no global keyword inside the function
#-have declared local variables
# NAME = ["Product Manager", "Riopo Wet"]
# def Qupengfei ():
# NAME = "Self" #只找自己的局部变量
# print (' I'm going to do ', NAME)
# Qupengfei () #打印我要搞自己
#-No declaration of local variables
# NAME = ["Product Manager", "Riopo Wet"]
# def Qupengfei ():
# name.append (' Xxoo ') #自己没有局部变量就找全局变量
# print (' I'm going to do ', NAME)
# Qupengfei () #打印我要搞 ["Product manager", "Riopo Wet"]

# If the contents of the function have the global keyword
#-have declared local variables
# NAME = ["Product Manager", "Riopo Wet"]
# def Qupengfei ():
# Global NAME
# NAME = "Self" # same as "local variable with no declaration of the same name"
# print (' I'm going to do ', NAME)
# Qupengfei () #打印我要搞自己
-# Error Example
# NAME = ["Product Manager", "Riopo Wet"]
# def Qupengfei ():
# NAME = "Self"
# Global NAME
# print (' I'm going to do ', NAME) #报错, global must be close to the function def
# Qupengfei ()
#-Local variables with no declaration of the same name
# NAME = ["Product Manager", "Riopo Wet"]
# def Qupengfei ():
# Global NAME
# NAME = ["Mao"] #OK的
# name.append (' Xxoo ')
# print (' I'm going to do ', NAME)
# Qupengfei () #打印我要搞 ["Mao"], the list of elements is ["Mao", ' Xxoo ')


# Summary
# If there is no global keyword inside the function, first read the local variable, no local variable reads the global variable, cannot be globally re-assigned (name= "FFF"), but for the mutable type (list, dictionary, etc.), you can manipulate the inner element.
# If there is a global keyword in the function, the variable is essentially the global variable and can read the re-assigned value name= "FFF"
# Spec: global variable name uppercase, local variable lowercase

#在定义局部变量的子程序内, local variables work, and in other places, global variables work

2.nonlocal keywords

Specify the upper-level variable, and if not, continue up until you find it, as in the following example:

Name = "Just Niang"
Def Weihou ():
Name = "Chen Zhuo"
Def Weiweihou ():
Global name # refers to Globals
Name = "Cool" # So the change is a global variable

Weiweihou ()
Print (name)

Print (name)
Weihou ()
Print (name) # just Niang---> Chen Zhuo---> Cool

Name = "Just Niang"
Def Weihou ():
Name = "Chen Zhuo"
Def Weiweihou ():
nonlocal name # nonlocal, specify the upper-level variable, and if not, continue up until you find it
Name = "Cool"

Weiweihou ()
Print (name)

Print (name)
Weihou ()
Print (name) # just Niang---> cool----> Just Niang

Three, nested functions

1. Definition

A function body contains one or more function bodies

2. Execution procedure of nested functions

#1. Name= ' Yyq '
#2. Def huangwei ():
# 4.1.name = "Zyh"
# 4.2.print (name)
# 4.3.def Liuyang ():
# 4.4.1.name = "YJJ"
# 4.4.2.print (name)
# 4.4.3.def Nulige ():
# 4.4.5.1.name = ' ZJQ '
# 4.4.5.2.print (name)
# 4.4.4.print (name)
# 4.4.5.nulige ()
# 4.4.liuyang ()
# 4.5.print (name)

#3. Print (name)
#4. Huangwei ()
#5. Print (name)

Iv. function as Variable

Let's look at a few examples:

# def foo ():
# print (' from foo ')
# Bar ()
# foo () #报错, bar () not defined

# def bar ():
# print (' from Bar ')
# def foo ():
# print (' from foo ')
# Bar ()
# foo () #执行通过

# def foo ():
# print (' from foo ')
# Bar ()
# def bar ():
# print (' from Bar ')
# foo () #执行通过

# def foo ():
# print (' from foo ')
# Bar ()

# foo () # Error, could not find bar ()

# def bar ():
# print (' from Bar ')

Summary: In the computer, the function is treated as a long string of strings into memory, to get a memory address, and the function name is equivalent to a variable name (house number), the function name parentheses is the memory address of the call function.

V. Recursion

1. Definition

A function call itself is called recursion, the maximum number of recursion is 999 times, the example is as follows:

# def Calc (n):
# print (n)
# if int (N/2) = = 0:
# return N
# res=calc (int (N/2))
# return Res
#
# Res=calc (#每一层都print一个数字)
# Print (res) #返回最后的结果1

2. Characteristics of recursion

There must be a definite end condition (so a return is required); each step into a deeper level of recursion, the problem size is less than the previous layer; Recursive efficiency is not high (recursive write bad, easy memory overflow)

One more example of asking the way:

# import Time
# person_list=[' Yyq ', ' zyh ', ' ljy ', ' ZSC ']
# def Ask_way (person_list):
# print ('-' *60)
# If Len (person_list) = = 0:
# return ' No one Knows '
# person=person_list.pop (0) #使得列表中的人不断减少 (problem size reduction), after Len (person_list) is to prevent the first pass in the empty list causes an error
# if person = = ' Linhaifeng ':
# return '%s ' said: I know that the South base is on the High Pond Road '%person
#
# print (' Hi-man [%s], dare to ask where the road is '% person ')
# print ('%s ' replied: I don't know, but read your eyes to the pig, you wait, I help you ask%s ... '% (person, person_list))
# Time.sleep (10)
# Res=ask_way (person_list) #第一个人不知道, so he went to ask another person, and so on and on, knowing the result, and then returning to the layer
#
# print ('%s ' results were:%res '% (person,res))
# return Res
#
# Res=ask_way (person_list) #把函数的返回值暂时保存, for the next sentence to print out
# Print (RES)

python05-namespaces/scopes/recursion

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.