4. Python basic quick view

Python is a simple and easy -to -learn and powerful programming language. This chapter will browse the basic grammar of Python. For details, you can see the reference document.

4.1. Note

Single-line comments in Python start with #, and multiple lines can use multiple # signs, as well as ''' and """, for example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# This is the comment

'''
This is also the annotation
'''

"""
This is still a comment
"""
print ("Hello!")

4.2. Indentation

Python uses indentation to represent code blocks, and the number of indented spaces is variable, but the statements in the same code block must contain the same number of indented spaces, otherwise it will cause a running error. Examples are as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#For loop
for i in range(5):
    print("in")
print("out")

# Output result
in
in
in
in
in
out

4.3. Variables and Data Types

Variables and variable types in Python do not need to be declared and are dynamic. Each variable must be assigned a value before use. The variable will be created after the variable is assigned, and the type of the variable is determined by the value assigned to it. For example:

1
2
3
4
5
6
 a = 10             # Integer variable
 print(type(a))
 a = 10.0           # Floating point variable
 print(type(a))
 a = "test"         # String
 print(type(a))
1
2
3
4
 # Output
 <class 'int'>
 <class 'float'>
 <class 'str'>

Several standard data types are common in Python: Immutable data: Number, String, Tuple; Variable data: List , Dictionary , Set . Here are a few:

4.3.1. String

Strings in Python (non-character type) are enclosed in single quotes '' or double quotes "", and some special characters are escaped with backslashes \. For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
 #!/usr/bin/python3
 str0 = 'Python'

 '''
 字符串索引和截取
 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
   0   1   2   3   4   5   (index from front)
  -6  -5  -4  -3  -2  -1   (index from back)
 :   1   2   3   4   5   : (taken from the front)
 :  -5  -4  -3  -2  -1   : (taken from the back)
 '''
 print (str0) # output the entire str0 string
 print (str0[0]) # output the first character of the string
 print (str0[-6]) # output the first character of the string
 print (str0[:]) # entire str0 string
 print (str0[2:]) # Output all characters starting from the third
 print (str0[:-2]) # output all characters from the first to the fourth
 print (str0 * 2) # output the string twice, it can also be written as print (2 * str0)
 print (str0 + "TEST") # connection string

Strings can be indexed or truncated, but the index cannot be modified, reassigned, etc.

4.3.2. List

Lists can complete the data structure implementation of most collection classes. The types of elements in the list can be different, it supports numbers, strings can even contain lists (so-called nesting). A list is a comma-separated list of elements written between square brackets [ ]. Like string indexing, list indexing starts at 0, the second index is 1, and so on.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
 #!/usr/bin/python3

 list0 = [ 'python', "test", 10, 10.0 ]
 list1 = [ 123, 'Python' ]

 print (list0) # output the complete list
 print (list0[0]) # output the first element of the list
 print (list[1:3]) # output from the second to the third element
 print (list[2:]) # output all elements starting from the third element
 print (tinylist * 2) # output the list twice
 print (list0 + list1) # link list

4.3.3. Tuple

Python’s tuples are similar to lists, except that the elements of the tuple cannot be modified. Use parentheses ( ) for tuples and square brackets [ ] for lists. Tuple creation is very simple, just add elements in parentheses and separate them with commas.

Example of use:

1
2
3
4
5
6
7
 #!/usr/bin/python3

 tup1 = ('Pyrhon', 'Test', 1997, 2000)
 tup2 = (1, 2, 3, 4, 5, 6, 7 )

 print ("tup1[0]: ", tup1[0])
 print ("tup2[1:4]: ", tup2[1:5])

4.5. Function

Functions can improve the modularity of the application and the reuse rate of the code. Python provides many built-in functions, such as print(), as well as user-defined functions.

In Python, a function is defined using the def keyword, and the general format is as follows:

def function name (parameter list):

function body

Example of use:

1
2
3
4
5
6
7
 #!/usr/bin/python3
 #define function my_function
 def my_function(test):
     print("Hello!"+ test)

 #use function my_function
 my_function(' Python')

4.6. Modules and Packages

4.6.1. Module

Python provides a way to get definitions from a file for use in a script or an interactive instance of the interpreter. Such a file is called a module; definitions in a module can be imported into another module or into the main module, using the import statement.

For example:

1
2
3
4
5
6
7
8
 #!/usr/bin/python3

 #Use the python standard module: sys, use the import statement
 import sys
 print('\nPython environment path:', sys.path)

 #Use the from ... import statement
 from periphery import I2C

4.6.2. Package

Packages are a form of managing Python module namespaces, using “dotted module names”.

For example, the name of a module is A.B, then it represents a submodule B in a package A. Just like when using a module, you don’t have to worry about the mutual influence of global variables between different modules, and you don’t have to worry about the duplication of module names between different libraries when you use the form of dot module names.

For the installation and download of the package, please refer to the previous section Installing python.

4.7. virtual environment

Python applications often use packages and modules that are not part of the standard library, and sometimes require a specific version of a package or module, because the application may need to fix a specific bug, or the application uses a previous version of the library interface. For example: If application A requires version 1.0 of a module, and application B requires version 2.0, these requirements conflict, installing version 1.0 or 2.0 will cause one application to not run, this problem can be solved by creating a virtual environment.

A virtual environment creates a self-contained directory tree containing the Python installation for a particular version of Python, plus a number of additional packages. Different applications can use different virtual environments, with different versions of packages and modules installed.

Starting from version 3.3, Python comes with a virtual environment venv. To install venv, use:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 # Install the virtual environment
 cat@lubancat:~$ sudo apt-get install python3-venv

 # Create and enter the project-test directory, and then create an independent Python operating environment: test_env
 cat@lubancat:~$ mkdir project-test && cd project-test
 cat@lubancat:~/project-test$ python3 -m venv .test_env

 cat@lubancat:~/project-test$ ls -al
 total 12
 drwxr-xr-x  3 cat cat 4096 Dec  7 10:38 .
 drwxr-xr-x 17 cat cat 4096 Dec  7 10:38 ..
 drwxr-xr-x  6 cat cat 4096 Dec  7 10:38 .test_env
 cat@lubancat:~/project-test$

 # Activation into the environment
 cat@lubancat:~/project-test$ source .test_env/bin/activate
 (.test_env) cat@lubancat:~/project-test$
 (.test_env) cat@lubancat:~/project-test$ pip list
 Package       Version
 ------------- -------
 pip           18.1
 pkg-resources 0.0.0
 setuptools    40.8.0
 (.test_env) cat@lubancat:~/project-test$

 # Export the package and module version numbers of the current virtual environment
 (.test_env) cat@lubancat:~/project-test$ pip3 freeze > requirements.txt
 # Package and module version numbers for installation requirements
 (.test_env) cat@lubancat:~/project-test$ pip3 install -r requirements.txt

 # Exit environment
 (.test_env) cat@lubancat:~/project-test$ deactivate
 cat@lubancat:~/project-test$

For more knowledge about virtual environments, you can search for the keywords virtualenv, venv and pipenv.