Python Basics
One, note (#)
The Python comment statement starts with a "#" character, and the comment can start anywhere on a line, and the interpreter ignores everything after the line #.
- Single-line Comment: 1 print ' Hello, world! ' # Print Hello,world
- Multiline Comment: A multiline comment is enclosed in a three-quote "" section that requires comments, for example:
1 " " 2 Hello, world. 3 and l like Python. 4 ""
3. Chinese note: Need to write on the file header:
# CODING=GBK or #coding =utf-8
Second, continue (\)
If a line of statements is too long, you can use a backslash \ To break it into lines, for example:
1 # Check conditions 2 if and 3 (shark_warnings = 0):4 Send_goto_beach_mesg_to_pager ()
In addition, there are two exceptions where a statement can cross rows without using backslashes. When using a closed operator, a single statement can span multiple lines, for example: You can write multiple lines with parentheses, brackets, curly braces. In addition, three quotation marks include the following string and can be written across lines.
Three or more statements constitute a code group (:)
Indenting the same set of statements constitutes a block of code, called a code group. Like if, while, Def, and class
Compound statement, 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).
Four, code groups are separated by different indentation
Python uses indentation to separate code groups. The hierarchical relationship of code is reflected by the same depth of space or tab indentation.
Recommendation: Use a width of four spaces to indent the width. Do not use tabs as indents.
Five, 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.
Import SYS; x = ' Foo '; Sys.stdout.write (x + ' \ n ')
It is not recommended to write this, which reduces the readability of the code. Guarantees a statement line of code.
Six, module
A module is a file that contains all of the functions and variables that you define, followed by a. PY name. Modules can be introduced by other programs to use functions such as functions in the module. This is also the way to use the Python standard library.
Each Python script file can be considered a module.
A module can contain directly run code blocks, class definitions, function definitions, or a combination of those.
Referencing modules with Import
##################### module structure and layout ######################################
1/usr/bin/env python#Start line2 3 "This is a test module" #Module Documentation: A brief description of the function of the module and the meaning of important global variables, accessible through module.__doc__4 5 ImportSys#Module Import: Import the required modules6debug = True#variable definition: defined here as a global variable7 classFooclass (object):# -----------|8 "Foo class" # | # class Definition: The class is defined when the module is imported. Class is class.__doc__ when the document variable9 Pass # -----------|Ten One defTest ():#function Definition: The function defined here is accessed through module.function (), and the function document variable is function.__doc__ A "test function" -Foo =Fooclass () - ifDebug: the Print 'ran test ()' - if __name__=='__main__':#Main program - -Test ()
################ #源于: http://www.cnblogs.com/NNUF/archive/2013/01/13/2858908.html###############################
Vii. Assignment of Value
1. Multivariate Assignment:
>>>x,y,z =, ' A string '
Can be seen as:x = 1,y = 2,z = ' A string '
When you assign a value this way, the objects on both sides of the equal sign are tuples:
>>> (x, y, Z) = (1, 2, ' a string ')
2. Link Assignment:
>>> y = x = x + 1
>>> x, y
(2, 2)
As you can see, the results of the 2 executions are the same. The description variable x and y are all reference addresses that store the integer object 1.
3. Incremental assignment: The equals sign can be combined with an arithmetic operator to re-assign the result of the calculation to
The variable on the left.
like x = x + 1 We can change to x+=1.
4. Multiple assignments:
>>> x = y = z = 1
Note: If you need to swap the values of two variables, use x, y = y,x. There is no need to introduce a third variable like the C language.
/* Two variable exchanges in the C language */
TMP = x;
x = y;
y = tmp;
Eight, identifiers
Identifiers are valid sets of strings that are allowed as names in a computer language. Some of them are keywords, constituent words
identifier of the word. An identifier like this cannot be used as an identifier, or it can cause a syntax error
- A valid Python identifier
Python identifier string rules are 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
Identifiers cannot start with numbers, except for underscore symbols, which are not allowed.
- Key words
Both the keyword list and the Iskeyword () function are put into the keyword module for review.
- Private underline identifiers
PYTHON specifies special variables with underscores as variable prefixes and suffixes.
?? _XXX import single underline without ' from module import * '
?? __xxx__ System Definition Name
?? Private variable names in the __xxx class
Core style: Avoid using underscores as the start of variable names
A class attribute that begins with a single underscore (_foo) cannot be accessed directly, and is accessed through the interface provided by the class and cannot be imported with "from XXX import *". A double underscore (__foo) represents a private member of a class; a double underscore (__foo__) represents a special method-specific identifier for Python, such as __init__ (), which represents the constructor of a class.
Detailed Summary reference:http://www.chengxuyuans.com/Python/67370.html
Ix. Management of inner lining
- Variable definition: In Python, there is no need for such explicit variable declaration statements, and variables are declared automatically the first time they are assigned . Like most other languages, variables can be used only after they are created and assigned.
- Dynamic type: No type declaration required
- Liner Allocation: No tube required, Python interpreter solves itself
- Reference count: Keeps track of objects in memory, and records how many references are in use for all objects (this should need to be used to Python higher order, temporarily do not learn, refer to: Www.csdn1 (# #) 23.com/html/itweb/20130717/7656_ 7657_7664.htm)
- Garbage collection: The garbage collector is responsible for freeing up 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. A specific situation can cause a circular reference.
Ten, the first procedure
#!/usr/bin/env python'maketextfile.py--Create text file'ImportOsls=Os.linesep#get filename whileTrue:fname= Raw_input ('Enter the filename:') ifos.path.exists (fname):Print "ERROR: '%s ' already exists"%fnameElse: Break#Get file content (text) linesall = []Print "\nenter lines ('. ' by itself to quit). \ n"#Loop until user terminates input whileTrue:entry= Raw_input ('>') ifEntry = ='.': Break Else: All.append (Entry)#write lines to file with proper line-endingFobj = open (fname,'W') Fobj.writelines (['%s%s'% (x, LS) forXinchAll ]) Fobj.close ()Print 'done!'
1 #!/usr/bin/env python2 'readtextfile.py--Read and display text file'3 4 #get filename5fname = Raw_input ('Enter FileName:')6 Print7 8 #attempt to open file for reading9 Try:TenFobj = open (fname,'R') One exceptioerror,e: A Print "* * * File Open error:", E - - Else: the #Display contents to the screen - forEachlineinchFobj: - PrintEachline, -Fobj.close ()
First knowledge of Python (1) __python Basics