Python for Mac day_2

Source: Internet
Author: User
Tags define local variable scope

1. Functions

Definition: A function that encapsulates a set of statements by a name (function name), and to execute the function, simply call the name of its functions

Characteristics:

    1. Reduce duplicate code
    2. To make the program extensible
    3. Make programs easier to maintain
Syntax definitions
def Sayhi ():# function name    print("Hello, I ' m nobody! "  # Call function

can take parameters

# The following code , a b =5,8 = a**bprint(c  )# changed to write Def with a function   Calc (x, y): #里面的x, y is     parameter =x**    yreturn# returns function execution result = Calc # result assigned to c variable ,,,,, a.b for argument print (c)  
2. Function parameters and Local variables

Parametric the memory unit is allocated only when called, releasing the allocated memory unit immediately at the end of the call. Therefore, the formal parameter is only valid inside the function. Function call ends when you return to the keynote function, you can no longer use the shape parametric

Arguments can be constants, variables, expressions, functions, and so on, regardless of the type of argument, and when a function call is made, they must have a definite value in order to pass these values to the parameter. It is therefore necessary to use the assignment, input and other methods to get the parameters to determine the value

Default parameters

defStu_register (name,age,country,course):Print("----Registered Student information------")    Print("Name:", name)Print("Age :", age)Print("Nationality:", Country)Print("Course:", course) Stu_register ("Wang Shanbao", 22,"CN","Python_devops") Stu_register ("Zhang Jiaochun"21st"CN","Linux") Stu_register ("Liu Lao Gen", 25,"CN","Linux")
#默认参数改写
#def stu_register(name,age,course,country = "CN" ):Key parameters

Under normal circumstances, to pass parameters to the function in order, do not want to order the key parameters can be used, just specify the parameter name, But remember a requirement is that the key parameters must be placed after the position parameter.

stu_register(age = 22 ,name = ‘alex‘ ,course = "python" ,)

Non-fixed parameter--*args (return tuple) **kwarges (return dictionary)

 #   def  stu_register (Name,age,*args): #   *args will change multiple incoming parameters into a tuple form  print   (Name,age,args) stu_register (  " alex  " , 22)  #   output  #  alex () #后面这个 () is args, just because no value is passed, so it is empty  
Stu_register ("Uncle_guo",1,"Nihao", {1:2},[1,2])     
# Output  # (' Uncle_guo ', +, (1, ' Nihao ', {1:2}, [1, 2]))
#can also have a **kwargsdefStu_register (Name,age,*args,**kwargs):#*kwargs will turn multiple incoming parameters into a dict form.    Print(Name,age,args,kwargs) stu_register ("Alex", 22)#Output#Alex () {} #后面这个 {} is Kwargs, just because no value is passed, so it is emptyStu_register ("Jack", 32,"CN","Python", sex="Male", province="Shandong")#Output#Jack (' CN ', ' Python ') {' Province ': ' Shandong ', ' sex ': ' Male '}
Local variables
‘‘‘

Global vs. local 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. Don't use "'"
Name ="Alex Li" defchange_name (name):Print("before change:", name) name="King Horn, a man with a Tesla."    Print(" after change", name) change_name (name)Print("look outside, do you have a name change?", name)#Output" "before Change:alex liafter change gold angle King, a man with Tesla look outside to see the name changed? Alex Li" "

3. Return value

To get the result of the function execution, you can return the result using the return statement

Attention:

    1. The function stops executing and returns the result as soon as it encounters a return statement, so can also be understood as a return statement that represents the end of the function
    2. If return is not specified in the function, the return value of this function is None

4. Recursion

" " inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function. Recursive characteristics: 1. There must be a definite end condition of 2. Each time you enter a deeper level of recursion, the problem size should be reduced by 3 compared to the last recursion. 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, whenever entering a function call, the stack will add a stack of frames, whenever the function returns, the stack will be reduced by a stack of frames. Because the stack size is not infinite, the number of recursive calls is too many, resulting in stack overflow)'def  Calc    (N):print(n)     if int (N/2) = =0        :return     nreturn calc (int (n/ 2)Calc ()output:10521
#递归函数实际应用案例, two-point search
data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35] defBinary_search (dataset,find_num):Print(DataSet)ifLen (DataSet) >1: Mid= Int (len (DataSet)/2) ifDataset[mid] = = Find_num:#Find it Print("Find Numbers", Dataset[mid])elifDataset[mid] > Find_num:#find the number on the left of mid 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 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) binary_search (data,66)

Higher order functions

def Add (a,b,f):     return F (a) +f (b) Res=add (3,-6,abs)#ABS (-10) outputprint (res)

Python for Mac day_2

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.