Parisgabriel:python Full Stack engineer (0 basics to Mastery) Tutorial 15th lesson (function nesting, variable scope)

Source: Internet
Author: User
Tags for in range function definition variable scope

ParisgabrielThank you for your support.



                 Stick to a daily subscription every day. Grey often thanks for being a dead powder also wide to

                      Python ai from beginner to proficient

Globals ()/locals () function :
    Globals() returns the dictionary of variables in the current global scope
    Locals() returns the dictionary of variables in the current local scope
function variables:
The function name is a variable, and it is bound when the DEF statement is created
FA1 = FA No parenthesis binding function FA1 = FA () return result
The variable name of a function can be a sequence exchange algorithm
A function can be passed as an argument to another function:
For example:

def myinput (FN):     = [5, 3, 1, 9, 7]    return  fn (L)    print(myinput (max))     Print (Myinput (min))     Print (Myinput (sum))     Print (Myinput (len))


A function can be a return value for another function:
For example:

defGet_op (): s= Input ("Qing shu ru Cao Zuo")ifs = ="Zui da":returnMaxelifs = ="Zui Xiao":returnminelifs = ="He":returnSumL= [2, 3, 4, 6, 5, 6, 9, 1]Print(L) F=Get_op ()Print(f (L))

Nesting of functions:
Function nesting definition refers to the use of DEF statements in a function to create other functions

Example:

def fn_outter (): Print ("Fn_outter is called ") def Fn_inner (): Print ("Fn_inner is called ") Fn_inner () Fn_inner () Print ("fn_outter call ends ") fn_outter ()

Scope of Python:
A scope is also called a namespace, which is a range of variables to look for when accessing variables
Python's 4 scopes:
Scope: English explanation abbreviation
Local scope (within functions) local (function) L
Outer nested function scope enclosing functio loc E
function definition module (file) scope Global (module) G
Python built-in module scope Builtin (python) B
Include relationships (built-in > Modules > External nested functions > Functions)
variable name lookup rules:
When accessing a variable, look for a local variable, then a variable inside a function that wraps outside of the function.
, then the global variable, and finally the built-in variable
L---> E---> G---> B
By default, variable name assignment creates or alters the current scope of the variable
Global statement:
Tells the explanation of the executor global statement to declare one or more variables,
The scope of these variables is the scope of the module level, also known as the global variable
Global DeclarationGlobal
Mapping variables that are manipulated by assignment statements to scopes inside module files
   Grammar
Global variable 1, variable 2, ....
   Description:
1. Global variables must be globally declared if they are to be assigned inside a function (otherwise, they will be considered to create local variables)
2. Global variables can be accessed directly within the function without being declared (the variable already exists and is associated with an object)
3. You cannot declare a local variable and then declare it as a global variable by using global, and this practice does not rule
4. Variable names in the global variables list cannot appear in the formal parameter list in this scope

nonlocal statement:
tells the interpreter that the Nonlocal declaration variable is not a local variable or a global variable
it is an outer nested function variable
syntax:
nonlocal variable name 1, Variable Name 2, ...
Description:
1. nonlocal statements can only be used inside nested functions
2. Accessing the nonlocal variable will operate on variables within the scope of the outer nested function
3. When there is When two or two layers of functions are nested, accessing the nonlocal variable only operates on the most recent layer of variables
4. The variable name in the variable list of the nonlocal statement, which cannot appear in the argument lists of this function

lambda expression (also known as anonymous function) (Greek alphabet: Enter)
  Role:
Create an anonymous function object
Similar to DEF but does not provide a function name
  Format:
lambda[parameter 1, parameters ...] : An expression
  Description
1. Lambda is just an expression that is used to create a function object
2. When a lambda expression is called, a colon (:) expression is executed first, and a reference relationship is returned for the result of the expression
3. A function created by a lambda expression can contain only one expression
4. Lambda is simpler than function and can be created and destroyed at any time, which helps to reduce the degree of program coupling.

 Function:
eval ()/EXEC () function
Eval (source, Globals=none, Local=none) executes a string srouce as an expression, returning the result of the expression execution
EXEC (source, Globals=none, Locals=none) executes a string source as a program


Practice:
Write a function called Hello (name), part of the code is as follows:
Count = 0
def hello (name):
Print (' Hello ', name)
... Here the code is omitted, the students need to fill out their own
... The code here needs to change the global variables to record how many times this function has been called.

Hello (' Xiao Zhang ')
Hello (' Xiao Li ')
Print (' Hello function called ', count, ' Times ') # 2 times

Count =0defHello (name):GlobalCount Count+ = 1Print("Hello", name) Hello ("name") Hello ("Xiaoli") Hello ("Xiaoliu") Hello ("Xiaowei") Hello ("Xiaozhang")


1. Write a lambda expression that determines whether the number of 2 +1 can be divisible by 5, or false if it can be divisible to return true
Cases:
FA = lambda x: .....
Print (FA (2)) # True
Print (FA (4)) # False

Lambda x: (x * * 2 + 1)% 5 = = 0print#  Trueprint#  false< /c7>

2. Write a lambda expression to find the maximum value of two variables
For example:
def mymax (x, y):
...
Mymax = lambda ...
Print (Mymax (100, 200)) # 200

def Mymax (x, y):     if x > y:        return  x    Else:        return y Print #  $  Lambdaifelseprint#  


1. Give an integer n, write a function myfac to calculate the n! (Factorial of N)
N! = 1 * 2 * 3 * 4 * ..... * N
Such as:
Print (MYFAC (5)) # 120

def MYFAC (n):     = 1     for in range (1, n + 1):        = x * i    return  x  Print(MYFAC (5))

2. Give an integer n and write a function to calculate MYFN (n):
1 + 2**2 + 3**3 + .... + N**n and
Such as:
Print (MYFN) #???

def Myfu (n):     = 0    for in range (2, n + 1):        + = x * *     xreturn  s  Print(Myfu (10))

3. Full number:
1 + 2 + 3 = 6 (6 for full number)
A factor of 6 for a single-and-A-zero (factor is the integer divisible by a number x is Y, then Y is the factor of x)
1 x 6 = 6
2 x 3 = 6
A complete number refers to the number of factors that are combined with and equal to itself, except for itself.
Ask for a full number and print it out.
Answer:
6
28
496
......

defMywqs (x): s=0 L= []     forIinchRange (1, x):ifX% i = =0:l.append (i) forIinchl:s+=Iifs = =x:returnTrueElse:        returnFalsei=0wqs=0 whileWqs < 5: I+ = 1ifMywqs (i) = =True:Print(i) Wqs+ = 1

cough again to the Blowing NB link
locals (), Globals ()
is a query function that returns information in a dictionary form.
function variables?
you just think of it as a global variable binding data and it's so simple to bind a statement block
What is a scope?
Scope is the extent to which a variable belongs to a range that is invalid
in other places there are generally 3 scopes and Python has 4
built-in variable local variable module global variable
The Special One is a range of two function nesting (outer nesting)
include relationships (built-in > Modules > External nested functions > Functions)
Built- in functions cannot be deleted or modified other scopes cannot have duplicate names with built-in functions
Otherwise, the built-in function fails to function only in the current space custom function
Each scope is irrelevant to the same space .
Global variables are directly declared by global using global regardless of any space
nonlocal can only use multi-layered nesting within nested functions to jump one layer
Lambda creates a function with an expression as if

Parisgabriel:python Full Stack engineer (0 basics to Mastery) Tutorial 15th lesson (function nesting, variable scope)

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.