First, python overview, variables

Source: Internet
Author: User

I. Overview of Python

1, Python is an object-oriented, interpreted scripting language. The syntax is concise, the writing efficiency is high, but the execution (bottom run) is inefficient (in general, the interpretation of language execution is less efficient than the compiled language).

Note: All the code in this blog is created in accordance with the Python3 standard.

2, the main language features are: Any statement can exist independently. And the code block starts with (:), notice the indentation space for each statement (the indentation format determines the inclusion and execution order of the statement), and the indentation of the space in Python is equivalent to the "{}" in Java, and there is no explicit requirement that a few spaces are required, In general, if this sentence is a clause containing or is the last statement, the sentence will be indented 4 spaces or a TAB key (formatted as follows).

The following code will execute the error:

#!/usr/bin/python#-*-Coding:utf-8-*-true: "    true""False    "

Executing the above code, the following error alert will appear:

$ python test.py    5    True:    ^indentationerror:unexpected indent  

In Python's code block, you must use the same number of indent spaces at the beginning of the line.

3, Python's basic grammar and Java,shell scripts have a lot of similarities, can be referred to both languages to learn.

Second, the Python file comments, statements,

The first statement of the 1.python file is similar to the declaration of the shell file, "#!" Interpreter path

#!/usr/bin/python

2. Notes

2.1 Single-line comments, beginning with "#", note: Quotes in Python are also paired

Print (' Hello python! ') print ("Hello python! ")

2.2 Multiline comments, enclosed in three single quotation marks ("" ") or double quotation marks (" "" ""), note: The quotation marks are in pairs.

"" "Python inside the constructor of the class can not use the keyword, in Python can not have ++,--, but in Java, the shell with let Var_name + + this is to enter the end" "" Print (' Life is short, Study Hard python! ', end=' \ n ')' This is the basic usage of the output function of Python3 print (self, *args, sep= ', end= ' \ n ', File=none) can change any of the parameters inside, end indicates what ends after the output * Args: Indicates indefinite length parameters, which will be described in detail in the following "print"life is too short to learn python! ', end=' ^_^ ') print (' Life is short, study hard python! ', end=' ^_^ ')      

Output Result:

Life is too short to learn python!
Life is too short to learn python! ^_^ life is too short to learn python! ^_^

Note: There are some special characters (', ", etc.) that can be used to write a string, with three single quotes or double quotation marks as a good workaround. At the same time, the newline output is.

The following will be an error:

Print (' Let ' t go ')

The following will output normally:

Print (' let ' s go! ')

The following will be an error:

Print ('---------------')print (' Spring sleep does not know every        mosquito bites the            dream of spring rain at night the            Moon Smile        ')  

Here is the line-break output:

#输出时空格换行等都不会忽略, even the blank line and the space are print ('---------------') print (' ' ' "      spring sleep        everywhere mosquito bites the            dream of spring rain at night the            Moon smile "        ) print ('---------------')  

The results are as follows:
---------------

Spring sleep does not feel Xiao
Mosquito bites everywhere
The dream comes the spring rain sound
The Moon smiles at night


---------------

Process finished with exit code 0

3. Spaces

A blank line separates between functions or methods of a class, representing the beginning of a new piece of code. The class and function entries are also separated by a line of blank lines to highlight the beginning of the function entry.

Blank lines are different from code indentation, and empty lines are not part of the Python syntax. When you write without inserting a blank line, the Python interpreter runs without errors. However, the purpose of a blank line is to separate the code of two different functions or meanings, which facilitates the maintenance or refactoring of future code.

Remember: Blank lines are also part of your program code.

Third, variable

3.1 Declaration of variables

Python's variable definitions, like shell naming, can be defined directly

3.1.1 Assigning a value to a single variable

Variable_name = value

3.1.2 Assigning the same value to multiple variables

Variable_name1=variable_name2=variable_name3......=value

3.1.2 Assigning different values to multiple variables

Variable_name1,variable_name2,variable_name3......=value1,value2,value3 ...

3.2 Naming conventions for variable names

1, letters, numbers, underline composition

2, the number can not start

3, strictly distinguish the letter case

4, can not directly use reserved words or keywords (all lowercase)

3.3 Scope of variables

3.3.1 Variable scope (scope) is a place where you can easily drop a hole in Python.
There are 4 scopes in Python, namely:

L (local) local scope: A variable defined in a function
In functions outside of the E (enclosing) closure function
G (Global) scope
B (built-in) built-in scopes
With the rules of L-E-and G--->b, that is: in the local can not find, will go to local outside the local search (such as closures), and can not find the overall look, and then to the built-in search.

123#局部变量 print (return glcprint (' global variable: ', global_variable)# print (GLC) Local variables cannot be called by print (Function_name ()) outside this function#局部变量只能在本函数中调用   

The results are as follows:

Global variables: 123
Call global variable in function: 123
345

3.3.2 Closure Package closure
Closure definition: If in an intrinsic function, a reference to a variable within an external function, but not at the global scope, the intrinsic function is considered a closure (closure).

This concept is well-represented in JavaScript.

Scopes in function nesting/closures:

DefExternal():     global a  #声明一个全局变量 a = 200 print ( ' local function call: ', a) b = 100 #创建外部函数变量  #定义内部函数  def internal (): # nonlocal b print ( ' variables that call external functions: ', b b = 200 #给外部函数的变量修改值 return b Internal ()  #执行内部函数 print (print ( ' external function result: ', external ())    

Operation Result:

unboundlocalerror:local variable ' b ' referenced before assignment

Error-Reference before assignment, Python3 has a keyword nonlocal to solve the problem, but in Python2 do not try to modify the variables in the closure.

There is also a hole in the closure:

From FunctoolsImport Wraps#导入模块 (Guide package)def wrapper (log): def external (F): Span class= "Hljs-meta" > @wraps (F) def internal (**kw): if false:log =  ' modified ' print (log) return Internal return external @wrapper (' first ') def abc  (): passprint (ABC ())   

There will also be a reference to the error before the assignment, because the interpreter detects the re-assignment in if False, so it does not look for the variable in the outer function of the closure (enclosing), but if Flase is not executed, this error occurs. Unless you also need to else:log= ' var ' or if True but it doesn't make sense to add a logical statement, try not to modify the variables in the closure.

It seems that it is not possible to implement the function of the counter in the usual way, because the internal count +=1 the error before the assignment, and the workaround: (or the nonlocal keyword in the PY3 environment)

Counter(Start):    count =[start]    Internal(): count[return count[return internalcount = Counter (0) inrange (print (count ())# 1,2,3,4,5,6,7,8,9,10count = Counter (0)print (count ())

3.3.3

Locals () and Globals ()
Globals ()
Global and Globals () are different, and global is the keyword used to declare a local variable as a global variable. Globals () and locals () provide a way for dictionary-based access to global and local variables

For example: If you need to define a local variable within function 1, the name of the other function 2 is the same, but also in function 1 to refer to the function 2.

var():    passF2' Just a String ' F1 = Globals () [return (Type (F1))print (F2 ())# Just A String# <type ' function ' >       


Locals ()
If you have used a Python web framework, you have experienced the need to pass a lot of local variables in a view function to the template engine, and then work on the HTML. While you can have some more clever practices, you still want to pass a lot of variables at once. You don't have to know how these grammars come about, what you do, you just need to get a general idea of what locals () is.
As you can see, locals () throws all the local variables together.

@app. Route ('/')View():    user = User.query.all ()    Article = Article.query.all ()    IP = Request.environ.get (return render_template (' index.html ', user=user,article = article, Ip=ip, s=s)#或者 Return render_template (' index.html ', **locals ())    

First, python overview, variables

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.