Python3 Basic syntax

May 10, 2021 01:00 Python3

Table of contents


By default, Python 3 source files are encoded in UTF-8, and all strings are unicode strings. Of course, you can also specify different encodings for source files:

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


  • The first character must be an alphabet letter or an underscore of ''.
  • The rest of the identifier consists of letters, numbers, and underscores.
  • The identifier is case sensitive.

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

Python reserves the word

Reserved words are keywords, and we can't use them as any identifier names. Python's standard library provides a keyword module that outputs all reserved words for the current version:

>>> import keyword
>>> keyword.kwlist



A single-line comment in Python begins with a hashtag, and a multi-line comment encloses a comment in three pairs of single quotes (') or three pairs of double quotes (').


Python's most distinctive feature is the use of indentation to represent blocks of code. The number of spaces indented is variable, but the statement of the same block of code must contain the same number of indented spaces.

Standard data type

There are six standard data types in Python:

  • Number (number)
  • String (string)
  • List (list)
  • Tuple (Tuple)
  • Set (Collection)
  • Dictionary (Dictionary)

Of the six standard data types for Python3:

  • Immutable data (3): Number (number), String (string), Tuple (tuple);
  • Variable data (3): List( list), Dictionary (dictionary), Set (collection).


  • Single and double quotes are used exactly the same in Python.
  • You can include a multi-line string with three pairs of quotation marks (' or '').
  • Escape character '''
  • Natural string, by adding r or R before the string. For example, r"this is a line with sn" will appear, not a line change.
  • Python allows the unicode string to be processed with the prefix u or U, such as u"this is an unicode string".
  • Strings are imm changed.
  • Cascading strings such as "this" "is" and "string" are automatically converted to this is string.
  • Strings can be connected together by the operator and repeated with the operator.
  • Strings in Python are indexed in two ways, starting at 0 from left to right and -1 from right to left.
  • Strings in Python cannot be changed.
  • Python does not have a separate character type, and one character is a string with a length of 1.
  • The syntax format for the interception of the string is as follows: variable (header: tail underseal: step).
word = '字符串'
sentence = "这是一个句子。"
paragraph = """这是一个段落,


print(str)                 # 输出字符串
print(str[0:-1])           # 输出第一个到倒数第二个的所有字符
print(str[0])              # 输出字符串第一个字符
print(str[2:5])            # 输出从第三个开始到第五个的字符
print(str[2:])             # 输出从第三个开始后的所有字符
print(str[1:5:2])          # 输出从第二个开始到第五个且每隔两个的字符
print(str * 2)             # 输出字符串两次
print(str + '你好')         # 连接字符串
print('hello\nrunoob')      # 使用反斜杠(\)+n转义特殊字符
print(r'hello\nrunoob')     # 在字符串前面添加一个 r,表示原始字符串,不会发生转义

Here r refers to raw, or raw string, which automatically escapes the backslash, for example:

>>> print('\n')       # 输出空行
>>> print(r'\n')      # 输出 \n

The above example output results:


Empty line

The functions are separated by empty lines or between the methods of the class, indicating the beginning of a new piece of code. Classes and function entrances are also separated by a row of empty lines to highlight the beginning of the function entry.

Unlike code indentation, empty lines are not part of the Python syntax. N o empty lines are inserted when writing, and the Python interpreter does not run in error. But the purpose of empty lines is to separate two pieces of code with different functions or meanings for later code maintenance or refactoring.

Remember: empty lines are also part of the program code.

Wait for user input

After pressing the enter key, the following program waits for user input:


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

In the above code, the "" Once the user presses the enter key, the program exits.

Multiple statements are displayed on the same line

Python can use multiple statements on the same line, using a hymn between statements (;) Split, here's a simple example:


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

Use the script to execute the above code, and the output is:


Executed using an interactive command line, the output is:

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

7 here represents the number of characters.

Multiple statements make up a code group

Indent the same set of statements to form a block of code, which we call a code group.

Compound statements such as if, while, def, and class, start with a keyword and end with a colon (:), followed by one or more lines of code that make up a code group.

We refer to the first line and subsequent code groups as a clause.

Here's an example:

if expression : 
elif expression :
else :

Print output

The print default output is newer, and if you want to implement a line not line change, you need to add end="" at the end of the variable:


# 换行输出
print( x )
print( y )
# 不换行输出
print( x, end=" " )
print( y, end=" " )

The above examples perform as follows:

a b

Import and from... import

In Python with import or from... import to import the appropriate module.

Import the entire module in the format: import somemodule

Import a function from a module in the format: from somemodule import somefunction

Import multiple functions from a module in the format: from somemodule import firstfunc, secondfunc, thirdfunc

Import all functions from a module in the format: from somemodule Import

Import the sys module

import sys
print('================Python import mode==========================')
print ('命令行参数为:')
for i in sys.argv:
    print (i)
print ('\n python 路径为',sys.path)

Import the argv, path member of the sys module

from sys import argv,path  #  导入特定的成员
print('================python from import===================================')
print('path:',path) # 因为已经导入path成员,所以此处引用时不需要加sys.path

Command-line arguments

Many programs can do something to see some basic information, and Python can use the -h parameter to view the parameter help information:

$ 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. ]