Python Learning notes (4)--functions

Source: Internet
Author: User

1. functions

A function is the encapsulation of a set of statements by a single name. to execute this function, simply call the name of its functions.

Features of the Function:

1. Reduce duplication of code

2. Extension of the course of the program

3. Make the program easier to maintain

Syntax definitions:
1 def Print_hello ()    # defines the function 2     print("Hello " )34# Call function
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

3. Default Parameters
1 def stu_register (name,age,course,country="CN"):

The Conntry parameter is not specified at the time of invocation, and the default is cn, if specified, with the value you specify.

4. 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.

5.Non-fixed parameters

If your function is not sure how many parameters the user wants to pass in the definition, you can use the non-fixed parameter

1 defStu_register (name,age,*args):#*args will change multiple incoming parameters into a tuple form.2     Print(name,age,args)3  4Stu_register ("Laozhang", 22)5 #Output6 #Laozhang () #后面这个 () is args, just because no value is passed, so it is empty7  8Stu_register ("Jack", 32,"CN","Python")9 #OutputTen #Jack (' CN ', ' Python ')

can also have a **kwargs

1 defStu_register (name,age,*args,**kwargs):#*kwargs will turn multiple incoming parameters into a dict form.2     Print(name,age,args,kwargs)3  4Stu_register ("Laozhang", 22)5 #Output6 #Laozhang () {} #后面这个 {} is kwargs, just because no value is passed, so it is empty7  8Stu_register ("Jack", 32,"CN","Python", sex="Male", province="Shandong")9 #OutputTen #Jack (' CN ', ' Python ') {' province ': ' Shandong ', ' sex ': ' Male '}
6. Local Variables
1Name ="Laozhang"2  3 defchange_name (name):4     Print("before Change:", Name)5Name ="Lao zhang, The best man after the old King."6     Print(" after Change", Name)7  8  9 change_name (name)Ten   one Print("look outside, Do you have a name change?", Name)

Output

1 before Change:laozhang 2 after the change Lao zhang, after the old king the most awesome person 3 outside to see the name change? Laozhang
7. Global variables and local variables variables defined in subroutines are called local variables, and variables defined at the beginning of a program are called Global Variables. 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. 8. Return Value

To get the result of the function execution, you can return the result with a return statement, which can be any data type

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
Various Functions 1. recursion

Definition: inside a function, other functions can be called. If a function calls itself internally, the function is a recursive function.

1 defCalc (n):2     Print(n)3     ifint (n/2) = =0:4         returnN5     returnCalc (int (N/2))6  7Calc (10)8  9 output:Ten10 one5 a2 -1

Recursive properties:

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, there are too many recursive calls, which can cause the stack to OVERFLOW.

Binary search of recursive function in practical application case

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) a   at   -Binary_search (data,66)
2. Anonymous functions

An anonymous function is one that does not require an explicit function to be specified

How to Use:
1 # this piece of code 2 def Calc (n): 3     return n**n4print(calc)5  6 # change to anonymous function 7 Lambda n:n**n8print(calc (10))

Use with other functions mainly

1 res = map (lambda x:x**2,[1,5,7,4,8])  2 for in res: 3     Print (i) 4 5 Output 6 1 7  8 ( 9 ) 64
3. Higher-order functions

A variable can point to a function, which can receive a variable, and a function can receive another function as a parameter, a function called a higher order Function.

1 def Add (x,y,f): 2     return F (x) + f (y)3  4  5 res = add (3,-6, Abs)6  Print(res)
4. Built-in Functions

first, the mathematical Operation class

ABS (x) Seek absolute value
1, the parameters can be integral type, can also be plural
2, If the parameter is a complex number, then return the modulus of the complex
Complex ([real[, imag]]) Create a complex number
Divmod (a, B) Separate fetch and remainder
Note: integral, floating-point types can be
Float ([x]) Converts a string or number to a float. If no parameter is returned 0.0
int ([x[, base]]) Converts a character to an int type, and base represents the binary
Long ([x[, base]]) Converts a character to a long type
Pow (x, y[, z]) Returns the Y power of X
Range ([start], stop[, step]) Produces a sequence that starts with 0 by default
Round (x[, N]) Rounded
Sum (iterable[, start]) Sum the Set
Oct (x) Convert a number to 8 binary
Hex (x) Converts an integer x to a 16-binary string
CHR (i) Returns the ASCII character corresponding to the integer i
Bin (x) Converts an integer x to a binary string
BOOL ([x]) Convert X to Boolean type

second, the Collection class operation

Basestring () Super class for STR and Unicode
cannot be called directly and can be used as isinstance judgment
Format (value [, format_spec]) Formatting the output string
Formatted parameter order starting from 0, such as "I am {0},i like {1}"
UNICHR (i) Returns the Unicode of the given int type
Enumerate (sequence [, start = 0]) Returns an enumerable object that returns a tuple for the next () method of the Object.
ITER (o[, Sentinel]) Generates an iterator for an object, and the second parameter represents a delimiter
Max (iterable[, args ...] [key]) Returns the maximum value in the collection
Min (iterable[, args ...] [key]) Returns the minimum value in the collection
Dict ([arg]) Create a data dictionary
List ([iterable]) To convert a collection class to another collection class
Set () Set Object instantiation
Frozenset ([iterable]) Produces an immutable set
STR ([object]) Convert to String type
Sorted (iterable[, cmp[, key[, reverse]]) Team Collection Sort
Tuple ([iterable]) Generate a tuple type
Xrange ([start], stop[, Step]) The xrange () function is similar to range (), but Xrnage () does not create a list, but instead returns a Xrange object that behaves like a list, but calculates the list value only when it is needed, which saves us memory when the list is Large.

third, Logical Judgment

All (iterable) 1, the elements in the collection are true when they are true
2, special, If the empty string returned to True
Any (iterable) 1, the elements in the collection have a true time for the true
2, special, If the empty string returned to False
CMP (x, Y) If x < y, returns a negative number; x = = y, returns 0;x > y, returns a positive number

Python Learning notes (4)--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.