Latest web development tutorials

Python3 basic grammar

Python3 basic grammar


By default, Python 3 source file inUTF-8 encoding, all strings are unicode strings.Of course, you can also specify a different encoding of the source file:

# -*- coding: cp-1252 -*-


  • The first character must be a letter of the alphabet or an underscore '_'.
  • Other partial identifiers with letters, numbers and underscores.
  • Identifiers are case sensitive.

In Python 3, the non--ASCII the identifiers are also allowed.

python reserved word

That is a reserved word keywords, we can not take them as any identifier name. Python's standard library provides a keyword module, you can export all of the keywords of the current version:

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']


Python in single-line comments begin with#, examples are as follows:


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

Implementation of the above code, the output is:

Hello, Python!

Multi-line comments can be used multiple number #:


# 第一个注释
# 第二个注释

print ("Hello, Python!") 

Implementation of the above code, the output is:

Hello, Python!

Line and indent

python most characteristic is the use of indentation to represent blocks of code without using curly braces ({}).

The number of spaces to indent is variable, but the same statement a code block must contain the same number of spaces to indent. Examples are as follows:

if True:
	print ("True")
	print ("False")

The following number of spaces to indent the code number of the last line of the statement is inconsistent, it will result in a runtime error:

if True:
    print ("Answer")
    print ("True")
    print ("Answer")
  print ("False")    # 缩进不一致,会导致运行错误

Due to the above procedures are inconsistent indentation, will appear like the following error:

 File "", line 6
    print ("False")    # 缩进不一致,会导致运行错误
IndentationError: unindent does not match any outer indentation level

Multi-line statement

Python is usually a line to finish a statement, but if the statement is very long, we can use the backslash (\) to implement multi-line statement, for example:

total = item_one + \
        item_two + \

In [], {}, or () in a multi-line statement, without using a backslash (\), for example:

total = ['item_one', 'item_two', 'item_three',
        'item_four', 'item_five']

type of data

the number of python has four types: integers, long integers, floating point and complex numbers.

  • An integer, as a
  • Long integers are relatively large integer
  • Float as 1.23,3E-2
  • Complex as 1 + 2j, 1.1 + 2.2j


  • python single and double quotes to use exactly the same.
  • Using triple quotes ( '' 'or' '') can specify a multi-line string.
  • Escape character '\'
  • Natural string, by prefixing the string plus r or R. As r "this is a line with \ n" is \ n displays, not line breaks.
  • python allows the processing of unicode string prefix u or U, such as u "this is an unicode string".
  • Strings are immutable.
  • Literally cascading strings, such as "this" "is" "string" will be automatically converted to this is string.
word = '字符串'
sentence = "这是一个句子。"
paragraph = """这是一个段落,

Blank lines

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

Perform the following procedure after pressing the Enter key will wait for user input:


input("\n\n按下 enter 键后退出。")

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:


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

Implementation of the above code, enter the result is:

$ python3

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 : 
elif expression : 
else : 

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 form of a script execution Python, command line parameters can receive input, you can use the specific reference line arguments Python 3 command .