Latest web development tutorials

Python basic grammar

Python language Perl, C and Java languages ​​have many similarities. However, there are some differences.

In this chapter we learn in the future on the basis of Python syntax lets you quickly learn Python programming.


First Python Program

Interactive Programming

Interactive programming not need to create a script file, through the Python interpreter in interactive mode came to write code.

On linux you just type Python commands in the command line to start the interactive programming, prompt as follows:

$ python
Python 2.7.6 (default, Sep  9 2014, 15:04:36) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 

Window on when installing Python is already installed default interactive programming client prompt window as follows:

python-shell

Enter the following text in python prompt, then press Enter to view operating results:

>>> print "Hello, Python!";

In Python 2.7.6 release, the above examples of output results are as follows:

Hello, Python!

Scripted Programming

Call the interpreter script parameters begin script until the script is finished. When the script is executed, the interpreter is no longer valid.

Let's write a simple Python script. All Python file will .py extension. The following source code copied to test.py file.

print "Hello, Python!";

Here, it is assumed that you have set up the Python interpreter PATH variable. Use the following command to run the program:

$ python test.py

Output:

Hello, Python!

Let's try another way to execute Python scripts. Modify test.py file as follows:

#!/usr/bin/python

print "Hello, Python!";

Here, suppose your Python interpreter / usr / bin directory, execute the script by using the following command:

$ chmod +x test.py     # 脚本文件添加可执行权限
$ ./test.py

Output:

Hello, Python!

Python identifiers

In python, the identifier with letters, numbers, and underscores.

In python, all identifiers can include letters, numbers, and the underscore (_), but can not start with a number.

python The identifiers are case sensitive.

Identifiers beginning with an underscore have a special significance. Class attribute single underscore (_foo) with representatives not directly accessible, the need for access through the interface provided by the class, and can not be imported with "from xxx import *";

Beginning with a double underscore (__foo) members representing the private class; double-underlined the beginning and end of Representative (__foo__) python dedicated in a special method of identification, such as __init __ () constructor on behalf of the class.


Python reserved characters

The following list shows the reserved word in Python. These reserved words can not be used as a constant or variable, or any other identifier names.

All Python keywords contain only lowercase letters.

and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield

Line breaks and indentation

Learning Python and other languages ​​is the biggest difference, Python code block does not use curly braces ({}) to control classes, functions and other logic. python most unique is to use indentation to write modules.

The number of blank indentation is variable, but all of the code block statement must contain the same number of blank indentation, this must be strictly enforced. As follows:

if True:
    print "True"
else:
  print "False"
 

The following code will execute error:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:test.py

 if True:
    print "Answer"
    print "True"
else:
    print "Answer"
    # 没有严格缩进,在执行时保持
  print "False"

Execute the code above, will appear the following error reminder:

$ python test.py  
  File "test.py", line 5
    if True:
    ^
IndentationError: unexpected indent

IndentationError: unexpected indent error python compiler is telling you "Hi, buddy, your file format is wrong, the tab may be blank and no alignment problems," all python to very strict format requirements.

IfIndentationError: unindent does not match any outer indentation level error indicating indentation you use inconsistent, some tab key to indent, plenty of spaces to indent, to be consistent.

Therefore, in the Python code block you must use the same number of spaces to indent the first line number.

I suggest you use a single tab or two spaces or four spaces for each indentation level, remember not to mix


Multi-line statement

Python statements generally as a new line for the statement terminator.

But we can use the slash (\) line will display multiple lines of statements, as follows:

total = item_one + \
        item_two + \
        item_three

Statement includes [], {}, or () brackets do not need to use multi-line connector. The following examples:

days = ['Monday', 'Tuesday', 'Wednesday',
        'Thursday', 'Friday']

Python quotes

Python receiving a single quote ( '), double quote ( "), triple quotes (' '' '' ') to represent strings must begin and end quotes of the same type.

Three of the quotes may consists of multiple lines, multiple lines of text written in shorthand syntax, the common language documentation string, the file in a particular location, is treated as a comment.

word = 'word'
sentence = "这是一个句子。"
paragraph = """这是一个段落。
包含了多个语句"""

Python comment

python using the single-line comments begin with #.

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:test.py

# 第一个注释
print "Hello, Python!";  # 第二个注释

Output:

Hello, Python!

Comments can in statements or expressions end of the line:

name = "Madisetti" # 这是一个注释

python multi-line comments using three single quotes ( '' ') or three double quotes ( "" ").

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:test.py


'''
这是多行注释,使用单引号。
这是多行注释,使用单引号。
这是多行注释,使用单引号。
'''

"""
这是多行注释,使用双引号。
这是多行注释,使用双引号。
这是多行注释,使用双引号。
"""

Python blank line

Between function or class method blank line, indicating the beginning of a new code. Between classes and also use the function entry line blank line began to highlight the function entry.

Blank lines and indenting of code is different from the blank line is not part of Python syntax. When not writing a blank line is inserted, Python interpreter to run it will not go wrong. But the role is a blank line separating two different function or meaning of the code, the code to facilitate future maintenance or remodeling.

Remember: a blank line is also part of the program code.


Waiting for user input

The following program pressing the Enter key will wait for user input:

#!/usr/bin/python

raw_input("\n\nPress the enter key to exit.")

The above code, "\ n \ n" will output the resulting output before two new blank line. Once the user presses the button, the program exits.


Show more than one statement on the same line

Python can be used in the same line multiple statements, use a semicolon between statements (;) division, the following is a simple example:

#!/usr/bin/python

import sys; x = 'w3big'; sys.stdout.write(x + '\n')

Implementation of the above code, enter the result is:

$ python test.py
w3big

Code group constitute multiple statements

Indent the same set of statements that make up a block of code, we call code groups.

Like if, while, def and class this compound statement, the first line to start with keywords, a colon (:) the end of one or more lines of code after the line of code group constitute.

We will be the first line of code group and later called a clause (clause).

The following examples:

if expression : 
   suite 
elif expression :  
   suite  
else :  
   suite 

Command line parameters

Many programs can perform some operations to view some of the basic letter, Python can use the -h parameter to view the help information for each parameter:

$ python -h 
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ... 
Options and arguments (and corresponding environment variables): 
-c cmd : program passed in as string (terminates option list) 
-d     : debug output from parser (also PYTHONDEBUG=x) 
-E     : ignore environment variables (such as PYTHONPATH) 
-h     : print this help message and exit 
 
[ etc. ] 

When we use the Python script in the form of execution, command line parameters can receive input, you can refer to the specific use Python command-line parameters .