Python basics-"python core programming"

Source: Internet
Author: User
Tags python script

?? Statements and syntax?? Variable assignment value?? Identifiers and keywords?? Basic style guide?? Memory management?? The first Python program 3.1 statements and syntax Python statements have some basic rules and special characters:
?? The pound sign (#) indicates that the following character is a Python comment
?? line break (\ n) is a standard line delimiter (usually one line of a statement)
?? backslash (\) to continue on line
?? Semicolon (;) Connect two statements in one row
?? Colon (:) separates the head and body of the code block
?? Statements (blocks of code) are represented by indented blocks (indent four space widths, avoiding tabs)
?? Different indentation depths separate different blocks of code
   ?? Python files are organized as modules (when a module becomes too large and drives too many functions, you should consider splitting the code out to create another module.) Note (#)     Similar to many Unix scripts, the Python comment statement starts with the # character and the comment can start anywhere on a line where the interpreter ignores everything after the line #. To use annotations correctly. Continue (\)     Python statements, typically separated by line breaks, that is, one statement at a line. A long line of statements can be broken down into lines using a backslash (\), as in the following example:        # check conditions        if (weather_is_ho t = = 1) and \        (shark_warnings = = 0):            Send_goto_beach_m Esg_to_pager ()     There are two exceptions. A statement can span rows without using backslashes.         When you use a closed operator, a single statement can span multiple lines, for example: You can write multiple lines with parentheses, brackets, curly braces.         In addition, a string containing three quotes can also be written across lines.     If you want to make a selection using backslash wrapping and wrapping with parenthesis elements, we recommend using parentheses, which makes readability better. Multiple statements make up a code group (:):    Indent the same set of statements that make up a block of code that we call a code group.     Compound statements such as if, while, Def, and class, the first line begins with a keyword, ends with a colon (:), and one or more lines of code after that line form the code group. We refer to the first line and the following code group as a clause (clause). The hierarchical relationship of code groups by different indents     code is manifested by the same depth of space or tab indentation.     Core style: Indent four space widths, avoid tabs          for a first use blankCharacter as a code block, the first question encountered is: how wide is the indentation appropriate? Two too few, six to eight and too many, so we recommend using four space widths.         It is important to note that tabs in different text editors represent blank widths, and if your code is applied across platforms, or is read and written by different editors, it is recommended that you do not use tabs.         using spaces or tabs both styles are supported by Python founder Guido  van Rossum and are included in the Python Code style guide documentation. Write multiple statements on the same line (;)     semicolon (;) Allows you to write multiple statements on the same line, separated by semicolons, and these statements cannot start a new block of code on this line.     It must be noted that writing multiple statements on the same line can greatly reduce the readability of your code, although Python allows you to do so without advocating it. Modules     Each Python script file can be considered as a module. The module exists in the form of a disk file. When a module becomes too large and drives too many functions, you should consider splitting out some code to build another module. The code in the     module can be a script that executes directly, or it can be a bunch of code similar to a library function that can be imported (import) by another module. The     module can contain directly-run blocks of code, class definitions, function definitions, or combinations of those.

3.2 Assigning values to variables

In the assignment operator Python language, the equal sign (=) is the primary assignment operator. Note that the assignment does not directly assign a value to a variable, although you might think that it should be the case with other language programming experience. In the Python language, objects are passed by reference. When assigning a value, whether the object is newly created or an existing one, the reference to the object (not the value) is assigned to the variable. Similarly, if you are more familiar with C, you will know that an assignment statement is actually treated as an expression (which can return a value). This is not suitable for Python, however, and Python's assignment statements do not return a value. Chained assignment
>>> y = x = x + 1>>> x, Y (2, 2)
Increment assignment
>>> x = 1>>> x + = 1>>> X2

Multivariate assignment (when assigning a value in this way, the objects on both sides of the equal sign are tuples)

>>> x, y, z = 1, 2, ' A string ' >>> x1>>> y2>>> z ' A string ' Python's multivariate assignment method can be achieved without intermediate change The value of two variables for the volume exchange.

3.3 identifiers

The legal Python identifier for Python identifier string rules is similar to most other high-level languages written in C:?? The first character must be a letter or an underscore (_)
?? The remaining characters can be letters and numbers or underscores
?? Case Sensitive Keywords


In addition to the keywords, Python has a collection of "built-in" names that can be used at any level of code, which can be set or used by the interpreter.        Although built-in is not a keyword, it should be treated as a "system reserved word" and not used by him.    However, there are situations that require overrides (that is, redefine, replace) them.     Python does not support overloaded identifiers, so there is only one name binding at any given time.    We can also tell the advanced reader that built-in is a member of the __builtins__ module, which is automatically imported by the interpreter before your program starts or before the >>> prompt in the interactive interpreter. Think of them as global variables that apply to any level of Python code. Private underline identifiers Python uses underscores to specify special variables as variable prefixes and suffixes.
Summary: _xxx without ' from module import * ' Import?? __xxx__ System Definition Name
?? Private variable names in the __xxx class
     Core style: Avoid underlining as the start of the variable name         Because the underscore has special meaning for the interpreter and is the symbol used by the built-in identifier, We recommend that programmers avoid using underscores as the start of variable names.         in general, variable name _xxx is considered "private" and cannot be used outside of a module or class.         It is good practice to use _xxx to represent variables when the variables are private. Because the variable name __xxx__ has a special meaning for Python, this naming style should be avoided for common variables. 3.4 Basic Style Guide     comments, documents, indents, identifiers     module structure and layout         # (1) Start line (Unix)       & nbsp # (2) Module documentation         # (3) module import         # (4) Variable definition         # (5) class Semantic         # (6) function definition         # (7) Main program         (1) Start line   &nbs P         Usually only use the starting line in a Unix-like environment, with the start line being able to enter only the script name to execute the script, no         need to invoke the interpreter directly.         (2) module documentation             briefly introduces the function of the module and the meaning of the important global variables, which can be accessed via module.__doc__ outside the module. Some content.          (3) module import             Import all modules required for the current module's code;The module is imported only once (when the current module is loaded), and the module import code inside the function is not executed unless the function is executing.          (4) Variable definition             The variables defined here are global variables, and all functions in this module can be used directly.             from a good programming style point of view, unless it is necessary to use local variables instead of global variables, if you persist in doing so, your code will not only be easy to maintain, but also improve performance and save memory.          (5) class definition statements             All classes need to be defined here. When the module is imported, the class statement is executed and the classes are defined. The document variable for the class is class.__doc__.          (6) Function definition statement             The function defined here can be accessed externally through module.function () , the DEF statement will be executed when the module is imported, and the function will be defined, and the function's document variable is function.__doc__.          (7) Main program             This part of the code will be executed regardless of whether the module is imported by another module or executed directly as a script. Usually there is not too much functional code here, but different functions are called according to the mode of execution.                           Figure 3–1 Typical Python file structureRecommended code style: Main program call Main () function
The main program code is usually similar to the code you saw earlier, checking the value of the __name__ variable and then executing the appropriate call (see the core note on the next page).
The code in the main program typically includes variable assignments, class definitions, and function definitions, and then examines __name__ to decide whether to invoke another function (usually called the Main () function) to complete the functionality of the module. The main program is usually doing these things. (We use test () instead of main () in the example above to avoid confusing you before reading the core notes. )
No matter what the name is, we want to emphasize that this is a good place to put the test code.        Most of the Python modules are used for import calls, and the module's regression test code should be called by the directly running modules.        Keep in mind that most of the modules are created to be called by others rather than as scripts that are executed independently.    Only one module, that is, the module that contains the main program, is executed directly, either by the user through the command line, or as a batch, or by a Unix cron task timed, or through a Web server call, or through a GUI. Core Note: __name__ indicates how the module should be loaded if the module is imported, the value of __name__ is the module name if the module is executed directly, the value of __name__ is ' __main__ ' 3.5 memory management
?? variable without prior declaration
?? Variable does not need to specify type
?? Programmers don't care about memory management
?? Variable names are "recycled"
?? Del statement can release resources directly
Variable definition
In Python, you do not need an explicit variable declaration statement, and the variable is declared automatically the first time it is assigned.
Like most other languages, variables can be used only after they are created and assigned.
Dynamic type
Not only does the variable name have to be declared in Python, but it does not require a type declaration.
In the Python language, the object's type and memory footprint are determined at run time.
Although the code is compiled into bytecode, Python is still an interpreted language.
When created-that is, the interpreter determines the type of the new object based on the syntax and the operands to the right.
After an object is created, a reference to that object is assigned to the variable on the left.    Memory allocation as a responsible programmer, we know that when allocating memory for a variable, the system resources are borrowed and the borrowed system resources should be freed after the use is exhausted.    The Python interpreter takes on a complex task of memory management, which greatly simplifies the writing of the application. You just need to be concerned about the problem you want to solve, as for the bottom of things to be assured that the Python interpreter to do it. Reference count Each object has a number of references, referred to as the reference count.

A reference count internal tracking variable, called a reference counter.

     When this object is no longer needed, that is, the reference count of this object becomes 0 o'clock, it is garbage collected. Increase reference count     When an object is created and assigned to a variable, the reference count of the object is set to 1.     When the same object (reference) is assigned to another variable,        or passed as a parameter to a function, method or class instance when,        or assigned to a window Port object, a new reference to the object, or an alias, is created (the object's reference count is automatically added to 1). Reference count of objects in     ?? object is created         x = 3.14   ?? Or another alias is created         y = x   ?? Or passed as a parameter to the function (new local reference)         Foobar (x)    ?? or become an element of the container object         myList = [123, X, ' XYZ '] reduce the reference count     When the object's reference is destroyed, the reference count is reduced. The most obvious example of         is that when a reference leaves its scope, this happens most often at the end of the function, when all local variables are automatically destroyed and the reference count of the object is reduced.     When a variable is assigned to another object, the reference count of the original object is automatically reduced 1:        foo = ' xyz '   # ' xyz '  1    &NB Sp   bar = foo     # ' XYZ '  2        foo = 123    # ' xyz '  1  &nbsp ; Other ways to reduce the reference count of objects include using the DEL statement to delete a variable (see the next section), or when an objectWhen a Window object is moved out (or the reference count of the container object itself becomes 0 o'clock).     The reference count for an object reduces:        in the following cases: A local reference has left its scope. such as Foobar () (see previous example) at the end of the function.        ?? The alias of the object is explicitly destroyed.             del y # or del x               ?? Remove y                from the current namespaces X's reference count minus one        ?? An alias of an object is assigned to another object             x = 123       ?? object is removed from a Window object             Mylist.remove (x)        ?? The Window object itself is destroyed             del myList # or goes out-of-scope garbage collection     The memory that is no longer being used is a machine called garbage collection System release.     Although the interpreter tracks the reference count of the object, the garbage collector is responsible for freeing the memory. The     garbage collector is a separate piece of code that is used to look for objects with a reference count of 0.         It is also responsible for checking those objects whose reference count is greater than 0 but should also be destroyed.          Specific situations can cause circular references.          A circular reference occurs when you have at least two objects referencing each other, which means that when all references are gone, theseReferences still exist, which means that reference counting alone is not enough.     Python's garbage collector is actually a reference counter and a cyclic garbage collector.     When an object's reference count becomes 0, the interpreter pauses, releasing the object and other objects that only the object can access (reachable).     as a reference count supplement, the garbage collector also pays attention to objects that are allocated a large amount (and those that are not destroyed by reference counting).     In this case, the interpreter pauses to attempt to clean up all unreferenced loops. Core tip: Replace module variables with local variables
A name like OS.LINESEP requires an interpreter to do two queries:
(1) Find the OS to confirm that it is a module,
(2) Find the LINESEP variable in this module. Because the module is also a global variable, we consume more system resources.
If you use a property in a function like this frequently, we recommend that you take a local variable alias for that property.
Variable lookups are much faster-always look for local variables before looking for global variables.
This is also a quicker technique for your program to run: Replace the frequently used module property with a local reference. The code runs faster and does not always have to knock on that long variable name.    3.6 related modules and development tools Python Code style Guide (PEP8), Python quick reference and Python FAQs are all important "tools" for developers. In addition, there are some modules that will help you become a good Python programmer.
?? Debugger:pdb
?? Logger:logging
?? Profilers:profile, hotshot, CProfile

Python basics-"python core programming"

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