Python Learning--02-python Basics--"4-variables and recursive functions"

Source: Internet
Author: User
Tags define local variable scope

6. Local variables and global variables

A variable defined in a subroutine is called a local variable, and a variable defined at the beginning of the program is called a global variable.

The global variable scope is the entire 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: Local variables work within subroutines that define local variables, and global variables work in other places. # #python中的def:d The EF keyword to define a function (1) Global variables
1 name='lhf' 2  def  change_name ():           4     print('  My name '5  6 change_name ()[This means running this function], must be run 

Output:

My name LHF.
(2) Local variables
1 1 name='lhf'2def  change_name ():3 3     Name=' handsome a pen '4 4     print(' my name  ', name)56 6 change_name ()7print(name)

Output:

My name is handsome, a great deal of handsome
(3) Use global name to convert local variables to global variables
1Name='LHF'2 defchange_name ():3     Globalname4Name='a handsome one.'5     Print('my name.', name)6 7 Change_name ()8 Print(name)

Output:

1 my name is handsome. 2 Handsome.

Explain the difference between a global variable and a local variable in your own words, and the difference between a static variable and an automatic variable:

All variables can be called throughout the project. For example, if I define a global variable in a standard module, I can call it either in Form 1 or form 2 or anywhere else. And the local variable is not, for example, I define a variable in a form, then this variable I can only use in this form. The static variable, that is, when I perform a process, its value is saved. The next time you perform this procedure, the value used is the new value (that is, the value that was generated after the last procedure was executed) and the dynamic variable does not save that value. When a procedure is executed, a static numeric variable is initialized to 0, and a static string variable is initialized to an empty string

7. Forward reference ' function is variable '

1defaction ():2Print 'In the action'3logger ()4Action ()5 Error Nameerror:GlobalName'Logger'  is  notdefined6 7 8deflogger ():9Print 'In the logger'10defaction ():11Print 'In the action'12logger ()13 14Action ()15 16 17defaction ():18Print 'In the action'19logger ()20deflogger ():21stPrint 'In the logger'Action ()

function = = Variable description function parameter and return value can also be function, this is important

8. Nesting functions and scopes

Looking at the title above means that the function can also be nested functions? Of course (1) nested functions

1Name ="Alex"2 3 defchange_name ():4Name ="Alex2"5 6     defchange_name2 ():7Name ="Alex3"8         Print("3rd Layer Printing", name)9 TenChange_name2 ()#calling the inner layer function One     Print("2nd Layer Printing", name) A  -  - Change_name () the Print("Outermost print", name)

Attention:
The function Hange_name () is run every time before printing

Output:

3rd layer Print Alex3 2nd layer Print Alex2 outermost print Alex

Note: at this point, what happens when you call Change_name2 () at the outermost layer?

Yes, it went wrong, why?

The scope is fixed when the function is defined and does not change as the call position changes

(meaning that it cannot be changed after the scope has been determined)

(2) Fixed scope

The scope is fixed when the function is defined and does not change as the call position changes

1 Example one: 2 name= ' Alex ' 3  4 def foo (): 5     name= ' LHF ' 6     def Bar (): 7         Print (name) 8     return Bar 9 Func=foo ( ) one func () 12 13 14 Case II: Name= ' Alex ', Def foo ():     name= ' LHF '     def Bar ():         name= ' Wupeiqi '         def TT ():             print (name),         Tt24     return bar25, Func=foo (), Func () ()

9. Recursive invocation

(1) Recursive invocation definition

Recursive invocation is a special kind of nested call, is a function call itself or call other functions to call themselves again, as long as the function calls each other can produce loops is recursive call, recursive call a solution, one is a logical idea, a big job into a small work gradually reduced, For example, a monk to move 50 pieces of stone, he thought, as long as the first move 49 pieces, the rest of the piece can be carried out, and then consider that 49, as long as the first move 48 pieces, the rest of the piece can be moved, recursion is a kind of thought, but in the program, is to rely on the function nested feature to achieve

Inside a function, you can call other functions. If you call itself directly or indirectly during a call to a function

(1) Example
1 def Calc (n):                 Calc: Calling a function from a function pointer.  2     print(n)3     if int (N/2) = = 0:4          return  n5     return calc (int (n/2))6 Calc (10)

Output:

10521
(2) recursive asking the way
1 #_*_coding:utf-8_*_2 __author__='Linhaifeng'3 Import Time4 5person_list=['Alex','Wupeiqi','Yuanhao','Linhaifeng']6 defAsk_way (person_list):7     Print('-'*60)8     ifLen (person_list) = =0:9         return 'no one knows.'Tenperson=person_list.pop (0) One     ifperson = ='Linhaifeng': A         return '%s said: I know, the old boy is in Shahe Hui Tak Commercial Building, the subway is'% Person -     Print('hi Beauty [%s], dare to ask where the road is'%Person ) -     Print('%s replied: "I do not know, but read your eyes know pig, you wait, I help you ask the%s ... "'%(person,person_list)) theTime.sleep (3) -res=Ask_way (person_list) -     #print ('%s ' results were:%res '% (person,res)) -     returnRes +  -  +  Ares=Ask_way (person_list) at  - Print(RES)

Output:

hi Beauty [Alex], dare to ask the way where Alex replied: "I do not know, but read your eyes know pig, you wait, I help you asked ['Wupeiqi','Yuanhao','Linhaifeng']...------------------------------------------------------------hi beauty Male [Wupeiqi], dare to ask the way in where Wupeiqi replied: "I do not know, but read your eyes know pig, you wait, I help you asked ['Yuanhao','Linhaifeng']...------------------------------------------------------------hi beauty Male [Yuanhao], dare to ask the way in where Yuanhao replied: "I do not know, but read your eyes know pig, you wait, I help you asked ['Linhaifeng']...------------------------------------------------------------Linhaifeng said: I know, the old boy is in Shahe Hui de commercial building, under the subway is

Note: above this is the circle to ask the names of the list, know Linhaifeng know the road, and then print out

(3) Recursive characteristics

1. There must be a clear end condition

2. Each time a deeper level of recursion is reached, the problem size should be reduced compared to the previous recursion

3. Recursive efficiency is not high, too many recursive hierarchy will lead to stack overflow (in the computer, function calls through the stack (stack) This data structure implementation, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will reduce the stack frame. Because the size of the stack is not infinite, the number of recursive calls is too many, resulting in stack overflow)(memory space)

Stack Literacy http://www.cnblogs.com/lln7777/archive/2012/03/14/2396164.html

Tail recursion optimization: http://egon09.blog.51cto.com/9161406/1842475

1data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35]2 3 4 defBinary_search (DataSet, Find_num):5     Print(DataSet)6 7     ifLen (DataSet) > 1:8mid = Int (len (DataSet)/2)9         ifDataset[mid] = = Find_num:#Find itTen             Print("Find Numbers", Dataset[mid]) One         elifDataset[mid] > Find_num:#find the number on the left of mid A             Print("\033[31;1m Find the number in mid[%s] left \033[0m"%Dataset[mid]) -             returnBinary_search (Dataset[0:mid], find_num) -         Else:#find the number on the right of mid the             Print("\033[32;1m Find the number in mid[%s] to the right \033[0m"%Dataset[mid]) -             returnBinary_search (Dataset[mid + 1:], Find_num) -     Else: -         ifDataset[0] = = Find_num:#Find it +             Print("We got the numbers.", dataset[0]) -         Else: +             Print("No, the number you're looking for [%s] is not in the list ."%find_num) ABinary_search (data, 66)

Output:

[1, 3, 6, 7, 9,, +, +, +,--), +, (+), (+), (+), [+],[20], 21, 22, 23, 30, 32, To find thenumber in mid[[] to theright [], tofind the number in mid[] to the right[]no points, to find the number [66] not in the list

Binary search: binary search, also known as binary retrieval, the basic idea of binary retrieval is that the elements in the dictionary are stored in an array in an orderly manner from small to large.

Python Learning--02-python Basics--"4-variables and recursive functions"

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.