Pthon Cultivation 5

Source: Internet
Author: User
Tags bbcode iterable

Function

One, Custom function

def: A keyword that represents a function

Function names: Names of functions

Function Body: A series of logical computations in a function

Parameters: Providing data for the function body

Return value: A value that finishes executing the function return

Example: Def count (x): #count: Name of the function you gave yourself (x): Parameter

b = count (x) #函数体, you give your function the specific work specified

Return b finishes executing the function body and encounters a return —————— > End---> Returns a value for the call to your function B when a function/procedure does not return a value with a definition returned by return, the Python interpreter implicitly returns none

Add:

1. Functions in programming languages are distinct from those of mathematical meanings, where functions in a programming language encapsulate a string of logic used to accomplish a particular function through a function name, and the mathematical definition of a function is an equation in which the equation enters the value of the dependent variable x and it gets a result y, This is similar to a programming language (it also passes in a parameter to get a return value), different functions with mathematical meanings, the same values are passed in, the results are necessarily the same and there is no modification of any variables (no modification of the state). While the functions in the programming language pass in parameters with the same return value that are not necessarily the same and can modify other global variable values (because the execution of a function a may depend on the result of another function B, B may get different results, even if you pass the same parameter to a, the result of a will certainly be different)

2. Functional programming is: first define a mathematical function (mathematical modeling), and then follow the mathematical model in the programming language to implement it. As for the benefits of how to do this and how to do it, look at the following functional programming.

Advantages of the function:

1. Code Reuse

2. Maintain consistency and ease of maintenance

3. Extensibility

Second, the parameters of the function

3. Positional parameters and keywords (standard call: Real participation parameter position one by one corresponds; keyword call: position without fixing)

4. Default parameters

5. Dynamic Parameters

def (P,*agrs,**kwagrs)

P, can accept only one value,

*args can accept multiple values and return with a tuple in a for loop,

**b, accept multiple values to return as a dictionary, dict={1:2} if the **kwargs in a worthwhile form will be an error, it must be **dict

Third, variable

Variables are divided into global variables and local variables

The 1.**global keyword is used to use global variables in functions or other local scopes. However, if you do not modify global variables, you can not use the Global keyword.

2.** is local if the global variable is not declared and the global variable is not modified. The global variable is used by default

3.**nonlocal is suitable for local functions in local functions, the most inner layer of local variables are set to the outer part is available, but not global.

Iv. built-in functions

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

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

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

4. Reflection

Callable (object) Checks whether object objects can be called
1, the class is can be called
2. Instances cannot be invoked unless the __call__ method is declared in the class
Classmethod () 1, annotations, to illustrate this way is a class method
2. Class methods can be called by the class or by instance
3. The class method is similar to the static method in Java
4. The self parameter is not required in a class method
Compile (source, filename, mode[, flags[, Dont_inherit]]) Compiles source into code or AST object. The code object can be evaluated by EXEC statement execution or eval ().
1. Parameter source: string or AST (Abstract Syntax Trees) object.
2, Parameter filename: code file name, if not read from the file code is passed some recognizable values.
3. Parameter model: Specifies the kind of compiled code. can be specified as ' exec ', ' eval ', ' single '.
4. Parameter flag and Dont_inherit: These two parameters are not introduced temporarily
Dir ([Object]) 1, without parameters, returns the list of variables, methods, and definitions in the current scope;
2, with parameters, returns the properties of the parameter, the method list.
3. If the parameter contains method __dir__ (), the method will be called. When the argument is an instance.
4. If the parameter does not contain __dir__ (), the method will collect the parameter information to the maximum
Delattr (object, name) Delete an object named Name property
eval (expression [, globals [, locals]]) Evaluates the value of an expression
ExecFile (filename [, globals [, locals]]) The usage is similar to exec (), the difference is that the execfile parameter filename is the file name, and the exec parameter is a string.
Filter (function, iterable) Constructs a sequence that is equivalent to [item for item ' in Iterable if function (item)]
1, Parameter function: Return a value of TRUE or false functions, can be none
2. Parameter iterable: A sequence or an iterative object
GetAttr (object, name [, Defalut]) Gets the properties of a class
Globals () Returns a dictionary that describes the current global symbol table
Hasattr (object, name) Determines whether the object contains an attribute named name
Hash (object) Returns the hash value of object if object is a hash table type
ID (object) Returns the unique identity of an object
Isinstance (object, ClassInfo) Determine if object is an instance of class
Issubclass (class, ClassInfo) Determine if it is a subclass
Len (s) Return collection length
Locals () Returns the current list of variables
Map (function, iterable, ...) Iterate through each element to perform a function operation
Memoryview (obj) Returns an object of a memory image type
Next (iterator[, default]) Similar to Iterator.next ()
Object () Base class
Property ([Fget[, fset[, fdel[, Doc]]) The wrapper class for property access, which can be set to access the setter and getter via C.x=value, etc.
Reduce (function, iterable[, initializer]) The merge operation, which starts with the first two parameters, and then the first two results are processed with the third merge, and so on
Reload (module) Reload Module
SetAttr (object, name, value) Setting property values
Repr (object) Changing an object to a printable format
Slice ()  
Staticmethod Declares a static method, which is an annotation
Super (type[, Object-or-type]) Referencing a parent class
Type (object) Returns the type of the object
VARs ([object]) Returns the variable of the object, if no argument is similar to the Dict () method
ByteArray ([Source [, encoding [, errors]]) Returns a byte array
1, if source is an integer, returns an initialized array of length source;
2. If source is a string, the string is converted to a sequence of bytes according to the specified encoding;
3. If source is an iterative type, the element must be an integer in [0, 255];
4. If source is an object that is consistent with the buffer interface, this object can also be used to initialize the ByteArray.
Zip ([iterable, ...]) is not understand, just see the matrix of the changing aspects

6. IO operation

File (filename [, mode [, BufSize]]) A constructor for the file type that opens a file that is created if the file does not exist and mode is write or append. Adding ' B ' to the mode parameter will manipulate the file in binary form. Adding ' + ' to the mode parameter will allow simultaneous read and write operations to the file
1. Parameter filename: Name of the file.
2, Parameter mode: ' R ' (read), ' W ' (write), ' a ' (append).
3, parameter bufsize: If 0 is not buffered, if 1 is a row buffer, if it is a number greater than 1 indicates the size of the buffer.
Input ([prompt]) Get user input
It is recommended to use raw_input because the function will not capture the user's error input
Open (name[, mode[, Buffering]) Open File
What is the difference from file? Recommended use of Open
Print Print function
Raw_input ([prompt]) Set input, input is handled as String

7. Other

Help ()--Information

__IMPORT__ ()--not very clear, see the phrase "Direct use of __import__ () is rare" after the No heart to look down

Apply (), buffer (), coerce (), intern ()---these are built-in functions that are out of date, so it does not explain

Pthon Cultivation 5

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.