Skip to content

Python Basics

This article will introduce the most basic processing and operations in Python.

1. Variables

In Python, variables do not need to be declared; they can be directly assigned values, as follows:

Python
1
2
3
a = 'Hello, World!'
b = 100
c = True

2. Output Variables

Variables' contents can be output using multiple methods, as follows:

2.1 Using the print() Method

The print() method directly outputs the content of the variable, as follows:

Python
1
2
a = 'Hello, World!'
print(a)

Output:

Text Output
1
100

2.2 Using the type() Method

The type() method returns the type of the variable and can be used with print(), as follows:

Python
1
2
a = type('Hello, World!')
print(a)

Output:

Text Output
1
<class 'str'>

2.3 Using the repr() Method

The repr() method returns detailed information about the variable and can be used with print(), as follows:

Python
1
2
a = repr('Hello, World!')
print(a)

Output:

Text Output
1
'Hello, World!'

Using the repr() method outputs strings with quotes, which helps distinguish between numbers and string representations of numbers.

2.4 Outputting Multiple Values

print() can output multiple variable values at once, making it convenient to output key program information, as follows:

Python
1
2
3
4
a = repr('Hello, World!')
b = repr(100)
c = repr(True)
print(a, b, c)

Output:

Text Output
1
'Hello, World!' 100 True

You can also use a "title, content" format for output, which makes it easy to check each variable's value, as follows:

Python
1
2
my_string = 'Hello, World!'
print('my_string:', repr(my_string))

Output:

Text Output
1
my_string: 'Hello, World!'

3. Basic Data Types

Python includes the following basic data types:

Data Type Description Example
None Null Value a = None
int Integer a = 100
float Float a = 100.0
str String a = 'Hello, World!
bool Boolean a = True
b = False

When writing Python code, avoid using data type names directly as variables, such as:

Python
1
int = 1

3.1 Null Value None

None is a value that represents "nothing," and can be checked using is or is not, as follows:

Python
1
2
3
4
a = None

print('a is None     Result:', a is None)     # Check if empty
print('a is not None Result:', a is not None) # Check if not empty

Output:

Text Output
1
2
a is None     Result: True
a is not None Result: False

3.2 Integers int, Floats float

int, float can perform mathematical operations and comparisons, as follows:

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
a = 5
b = 3

print('a + b        Result:', a + b)        # Addition
print('a - b        Result:', a - b)        # Subtraction
print('a * b        Result:', a * b)        # Multiplication
print('a / b        Result:', a / b)        # Division
print('a ** b       Result:', a ** b)       # Exponentiation
print('a // b       Result:', a // b)       # Floor division
print('a %  b       Result:', a % b)        # Modulo
print('int(a / b)   Result:', int(a / b))   # Truncate to integer
print('round(a / b) Result:', round(a / b)) # Round to nearest integer
print('a == b       Result:', a == b)       # Equal
print('a != b       Result:', a != b)       # Not equal
print('a > b        Result:', a > b)        # Greater than
print('a >= b       Result:', a >= b)       # Greater than or equal
print('a < b        Result:', a < b)        # Less than
print('a <= b       Result:', a <= b)       # Less than or equal

Output:

Text Output
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
a + b        Result: 8
a - b        Result: 2
a * b        Result: 15
a / b        Result: 1.6666666666666667
a ** b       Result: 125
a // b       Result: 1
a %  b       Result: 2
int(a / b)   Result: 1
round(a / b) Result: 2
a == b       Result: False
a != b       Result: True
a > b        Result: True
a >= b       Result: True
a < b        Result: False
a <= b       Result: False

3.3 Strings str

str can perform string concatenation, formatting, equality/comparison (i.e., alphabetical order), and containment checks, as follows:

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
a = 'Hello, '
b = 'World!'
c = 'Hello, World'

print('a + b  Result:', a + b)    # Concatenation
print(f'a + b  Result: {a + b}')  # Formatting
print('a > b  Result:', a > b)    # Comparison
print('a < b  Result:', a < b)    # Comparison
print('a == b Result:', a < b)    # Equality check
print('a in c Result:', a in c)   # Containment check

print('Using single quotes for strings                :', '"abc"')
print('Using double quotes for strings                :', "'abc'")
print('Using triple single quotes for strings         :', '''abc''')
print('Using triple double quotes for strings         :', """abc""")
print('Using triple single/double quotes for multiline strings:', """
123
abc
xyz
""")
print('Using escape character \ for special characters:', '\'abc\'')

Output:

Text Output
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
a + b  Result: Hello, World!
a > b  Result: False
a < b  Result: True
a == b Result: True
a in c Result: True
Using single quotes for strings                : "abc"
Using double quotes for strings                : 'abc'
Using triple single quotes for strings         : abc
Using triple double quotes for strings         : abc
Using triple single/double quotes for multiline strings:
123
abc
xyz

Using escape character \ for special characters: 'abc'

Generally speaking, it is recommended to use formatted string generation (called f-string in Python), which makes the code more intuitive compared to simple string concatenation with plus signs.

The syntax structure of f-string is as follows:

3.4 Booleans bool

bool can perform logical operations, as follows:

Python
1
2
3
4
5
6
7
8
9
t = True
f = False

print('t is True  Result:', t is True)  # Truth check
print('t is f     Result:', t is f)     # Comparison
print('t is not f Result:', t is not f) # Comparison
print('t and f    Result:', t and f)    # AND
print('t or  f    Result:', t or f)     # OR
print('not t      Result:', not t)      # NOT

Output:

Text Output
1
2
3
4
5
6
t is True  Result: True
t is f     Result: False
t is not f Result: True
t and f    Result: False
t or  f    Result: True
not t      Result: False

4. Common Data Types

In addition to basic data types, Python also provides some very common data types.

4.1 Lists list

A list is an ordered collection of several elements, similar to arrays Array in other programming languages.

Elements in Python lists can be of any type and do not have to be of the same type, such as:

Python
1
2
l = [] # Empty list
l = [1, 2, 3.3, True, 'Hello, World!']

When writing Python code, avoid using data type names directly as variables, such as:

Python
1
list = [1, 2, 3]

Common operations supported by lists are as follows:

Python
 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
l = [3, 2, 1]

# Adding elements
l.append(4)
print('After adding element:', l)

# Removing elements
x = l.pop()
print('Popped element:', x)
print('After popping element:', l)

# Merging lists
l.extend([7, 8, 9])
print('After merging lists:', l)

# Getting the first element (index 0)
print('Getting the first element:', l[0])

# Getting the last element (can specify index -1)
print('Getting the last element:', l[-1])

# Getting elements by index range
# Rule: `[start_index:end_index]`, includes start_index but excludes end_index
print('Getting elements from index 2 to the end:', l[1:])
print('Getting elements from index 2 to index 4:', l[1:4])
print('Getting elements from the second-to-last to the end:', l[-2:])

# Modifying elements
l[0] = 'Hello, World!'
print('After modifying element:', l)

# Iterating through elements
print('Iterating through elements:')
for x in l:
    print('    Value =', x)

# Iterating through elements with their indices
print('Iterating through elements with their indices:')
for index, x in enumerate(l):
    print('    Index =', index, ', Value =', x)

# Reversing the list
l.reverse()
print('After reversing the list:', l)

# Getting the number of elements in the list
print('Number of elements in the list:', len(l))

# Sorting
# Note: Cannot sort lists with mixed numbers and strings
l = [4, 3, 6, 2, 7, 1]
l.sort()
print('After sorting:', l)

Output:

Text Output
 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
After adding element: [3, 2, 1, 4]
Popped element: 4
After popping element: [3, 2, 1]
After merging lists: [3, 2, 1, 7, 8, 9]
Getting the first element: 3
Getting the last element: 9
Getting elements from index 2 to the end: [2, 1, 7, 8, 9]
Getting elements from index 2 to index 4: [2, 1, 7]
Getting elements from the second-to-last to the end: [8, 9]
After modifying element: ['Hello, World!', 2, 1, 7, 8, 9]
Iterating through elements:
    Value = Hello, World!
    Value = 2
    Value = 1
    Value = 7
    Value = 8
    Value = 9
Iterating through elements with their indices:
    Index = 0 , Value = Hello, World!
    Index = 1 , Value = 2
    Index = 2 , Value = 1
    Index = 3 , Value = 7
    Index = 4 , Value = 8
    Index = 5 , Value = 9
After reversing the list: [9, 8, 7, 1, 2, 'Hello, World!']
Number of elements in the list: 6
After sorting: [1, 2, 3, 4, 6, 7]

4.2 Tuples tuple

Tuples are similar to lists and are also ordered collections of several elements, but tuples cannot be modified once created.

Elements in Python tuples can be of any type and do not have to be of the same type, such as:

Python
1
2
t = tuple() # Empty tuple
t = (1, 2, 3.3, True, 'Hello, World!')

When writing Python code, avoid using data type names directly as variables, such as:

Python
1
tuple = (1, 2, 3)

Since parentheses used to represent tuples might be confused with regular parentheses, when defining a tuple with only one element, you need to add an extra comma to indicate this, as follows:

Python
1
2
t = (1,)
print(type(t))

Output:

Text Output
1
<class 'tuple'>

4.3 Dictionaries dict

Dictionaries are unordered collections of several elements organized in Key-Value pairs, similar to maps Map in other programming languages.

In Python dictionaries, Keys are usually strings, while Values can be of any type and do not have to be of the same type, such as:

Python
1
2
3
4
5
6
d = {} # Empty dictionary
d = {
  'a'   : 1,
  'b'   : 'Hello, world!'
  'isOK':  True,
}

When writing Python code, avoid using data type names directly as variables, such as:

Python
1
dict = {'a': 1}

Common operations supported by dictionaries are as follows:

Python
 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
34
35
36
37
38
39
40
41
d = {'a': 1}

# Adding/Modifying elements
d['b'] = 2
print('After adding/modifying elements:', d)

# Removing elements
x = d.pop('b')
print('Popped element:', x)
print('After removing element:', d)

# Merging dictionaries
d.update({'x': 9})
print('After merging dictionaries:', d)

# Getting elements
print('Getting element with key a:', d['a'])

# Getting element, returning None if it does not exist
print('Getting element with key xxx, returning None if it does not exist:', d.get('xxx'))

# Getting element, returning default value if it does not exist
print('Getting element with key xxx, returning default value if it does not exist:', d.get('xxx', 'Default'))

# Getting keys list
print('Getting keys list:', list(d.keys()))

# Getting values list
print('Getting values list:', list(d.values()))

# Modifying elements
d['a'] = 'Hello, World!'
print('After modifying element:', d)

# Iterating through elements
print('Iterating through elements:')
for k, v in d.items():
    print('    Key =', k, ', Value =', v)

# Getting the number of elements in the dictionary
print('Number of elements in the dictionary:', len(d))

Output:

Text Output
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
After adding/modifying elements: {'a': 1, 'b': 2}
Popped element: 2
After removing element: {'a': 1}
After merging dictionaries: {'a': 1, 'x': 9}
Getting element with key a: 1
Getting element with key xxx, returning None if it does not exist: None
Getting element with key xxx, returning default value if it does not exist: Default
Getting keys list: ['a', 'x']
Getting values list: [1, 9]
After modifying element: {'a': 'Hello, World!', 'x': 9}
Iterating through elements:
    Key = a , Value = Hello, World!
    Key = x , Value = 9
Number of elements in the dictionary: 2

4.4 Sets set

Sets are unordered collections of non-repeating elements.

Elements in Python sets can be of any type and do not have to be of the same type, such as:

Python
1
2
s = set() # Empty set
s = {1, 2, 'Hello, world!', True}

When writing Python code, avoid using data type names directly as variables, such as:

Python
1
set = {1, 'a'}

Common operations supported by sets are as follows:

Python
 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
s = {1, 2, 'a'}

# Adding elements
s.add(3)
print('After adding element:', s)

# Removing elements
s.remove('a')
print('After removing element:', s)

# Set intersection
print('Set intersection:', s & {2, 3, 4})
# Set union
print('Set union:', s | {7, 8, 9})
# Set difference
print('Set difference:', s - {1, 2})

# Converting to list
print('Converting to list:', list(s))

# Iterating through elements
print('Iterating through elements:')
for x in s:
    print('    Value =', x)

# Getting the number of elements in the set
print('Number of elements in the set:', len(s))

# Removing duplicates from list
l = [1, 1, 2, 3, 4, 4, 4, 5, 6]
print('Removing duplicates from list:', list(set(l)))

Output:

Text Output
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
After adding element: {3, 1, 2, 'a'}
After removing element: {3, 1, 2}
Set intersection: {2, 3}
Set union: {1, 2, 3, 7, 8, 9}
Set difference: {3}
Converting to list: [3, 1, 2]
Iterating through elements:
    Value = 3
    Value = 1
    Value = 2
Number of elements in the set: 3
Removing duplicates from list: [1, 2, 3, 4, 5, 6]

4.5 Mutual Nesting

Lists, dictionaries, and sets can be mutually nested to create complex data structures, such as:

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
data = [
    {
        'name'  : 'Tom',
        'age'   : 30,
        'titles': ( 'Programmer', 'Writer' )
    },
    {
        'name'  : 'Jerry',
        'age'   : 17,
        'titles': { 'Student' }
    }
]

Complex data consisting of basic data types, lists, tuples, and dictionaries can be output as JSON strings using Python's built-in json library, such as:

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import json

data = [
    {
        'name'  : 'Tom',
        'age'   : 30,
        'titles': ( 'Programmer', 'Writer' )
    },
    {
        'name'  : 'Jerry',
        'age'   : 17,
        'titles': [ 'Student' ] # Note: This is a list
    }
]
result = json.dumps(data, indent=2)
print(result)

Output:

Text Output
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
[
  {
    "name": "Tom",
    "age": 30,
    "titles": [
      "Programmer",
      "Writer"
    ]
  },
  {
    "name": "Jerry",
    "age": 17,
    "titles": [
      "Student"
    ]
  }
]

5. Conditional Handling with if-elif-else Syntax

In Python, conditional handling is performed using if ... elif ... else, such as:

Python
1
2
3
4
5
6
7
8
9
i = 80
if i >= 90:
    print('Excellent')
elif i >= 75:
    print('Good')
elif i >= 60:
    print('Average')
else:
    print('Poor')

Output:

Text Output
1
Good

Conditional handling can also be nested to implement more complex controls, such as:

Python
1
2
3
4
5
6
7
i = 42
if i % 2 == 0:
    print('Even number')
    if i % 3 == 0:
      print('Divisible by 3')
else:
    print('Odd number')

Output:

Text Output
1
2
Even number
Divisible by 3

6. Loop Handling with for and while Syntax

In Python, loops can be handled using for ... or while ....

6.1 for Loops

for loops are generally used for known loop counts, such as iterating over lists, as follows:

Python
1
2
3
l = ['Tom', 'Jerry', 'Lucy']
for x in l:
    print(x)

Output:

Text Output
1
2
3
Tom
Jerry
Lucy

You can also use range(...) to directly specify the number of iterations, as follows:

Python
1
2
for i in range(3):
    print(i)

Output:

Text Output
1
2
3
0
1
2

You can also use enumerate(...) to iterate over lists and obtain indices simultaneously, as follows:

Python
1
2
3
l = [ 'a', 'b', 'c', 'd' ]
for i, c in enumerate(l):
    print(f'{c} index is {i}')

Output:

Text Output
1
2
3
4
a index is 0
b index is 1
c index is 2
d index is 3

6.2 while Loops

while loops are generally used for known loop conditions. The loop executes as long as the condition is met and ends when the condition is no longer satisfied, as follows:

Python
1
2
3
4
5
i = 2
while not (i % 2 == 0 and i % 3 == 0 and i % 5 == 0):
    i = i + 1

print('Number divisible by 2, 3, and 5:', i)

Output:

Text Output
1
Number divisible by 2, 3, and 5: 30

When using while loops, be especially careful with the condition setting to avoid infinite loops caused by conditions that are always true.

6.3 Skipping, Interrupting Loops

During the loop process, you can use the continue statement to immediately jump to the next iteration or use the break statement to terminate the entire loop, as follows:

Python
1
2
3
4
5
6
7
for i in range(100):
    if i < 2:
        continue

    if i % 2 == 0 and i % 3 == 0 and i % 5 == 0:
        print('First number within 100 divisible by 2, 3, and 5:', i)
        break

Output:

Text Output
1
First number within 100 divisible by 2, 3, and 5: 30

7. Functions

Functions are reusable blocks of code that reduce coding complexity, such as:

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def plus(a, b):
    return a + b

questions = [
    [1, 2],
    [4, 5],
    [9, 3],
]

for x in questions:
    result = plus(x[0], x[1])
    print(result)

Output:

Text Output
1
2
3
3
9
12

7.1 Function Parameters

In the example above, the plus function contains two parameters a and b as input parameters. These input parameters can be directly used inside the function for processing.

Additionally, function parameters support default values. Parameters with default values do not need to be specified when calling the function, as follows:

Python
1
2
3
4
5
def hello(name='my friend'):
    print('Hello!', name)

hello()
hello('Tom')

Output:

Text Output
1
2
Hello! my friend
Hello! Tom

Function parameters can also be called using parameter=value without strictly following the order, as follows:

Python
1
2
3
4
5
6
def hello(name='my friend', message='What a day!'):
    print('Hello!', name)
    print(message)

hello('Tom')
hello(message='How is going', name='Jerry')

Output:

Text Output
1
2
3
4
Hello! Tom
What a day!
Hello! Jerry
How is going

7.2 Function Return Values

The return statement is used to return the function's return value. Besides returning a single value, functions can also return multiple values at once, as follows:

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def check_score(score):
    if score >= 90:
        return True, 'Excellent'
    elif score >= 75:
        return True, 'Good'
    elif score >= 60:
        return True, 'Average'
    else:
        return False, 'Poor'

result = check_score(90)
print('Using a single variable to receive:', result)

is_ok, result = check_score(80)
print('Using corresponding number of variables to receive:', is_ok, result)

Output:

Text Output
1
2
Using a single variable to receive: (True, 'Excellent')
Using corresponding number of variables to receive: True Good

8. Importing Modules with import Statement

In more complex projects, code is often placed in multiple different scripts for easier maintenance and management.

When needing to call code between scripts, the import statement is used to import modules.

Imported Script Location Import Method
Python script in the same directory import {script name}
Python script in a subdirectory import {directory name}.{script name}
Importing specific parts from {script name} import {object 1}, {object 2}, ...

Additionally, for external scripts with long names, you can use import xxx as yyy to assign aliases, as follows:

Python
1
2
3
4
5
6
7
8
9
# a.py script
def hello():
    print('Hello from a.py')

def hello2():
    print('Hello2 from a.py')

def hello3():
    print('Hello3 from a.py')
Python
1
2
3
# sub_folder/b.py script
def hello():
    print('Hello from sub_folder/b.py')
Python
1
2
3
4
5
6
7
8
9
# main.py script
import a                     # Import a
import sub_folder.b as b     # Import sub_folder/b and assign alias b
from a import hello2, hello3 # Import hello2, hello3 from a

a.hello()
b.hello()
hello2()
hello3()

Output:

Text Output
1
2
3
4
Hello from a.py
Hello from sub_folder/b.py
Hello2 from a.py
Hello3 from a.py

The description of import here is only the simplest commonly used part. For a complete and detailed introduction to import, please refer to professional tutorials.

8.1 Scripts in DataFlux Func

Due to the special mechanism of script management in DataFlux Func, scripts in DataFlux Func do not exist as files but are stored in databases. Therefore, importing other scripts in DataFlux Func differs from original Python implementations.

In DataFlux Func, Python scripts are organized in two layers: the first layer is the "Script Collection", and the second layer is the "Script". A script collection is merely a collection of scripts and is not a "folder".

Both script collections and scripts have IDs and are related. In a certain script collection, the script ID must be {associated script collection ID}__{script name} (with two underscores in between), as shown in the figure below:

8.2 Importing Scripts in DataFlux Func

Assume there are the following script collections and scripts:

Then, the import methods are as follows:

Imported Script Location Import Method
Python script in the same collection import __{script name}
or import {script ID}
Python script in another collection import {script ID}
Importing specific parts from {script name} import {object 1}, {object 2}, ...

For Python scripts in the same collection, it is recommended to use import __{script name} for importing, so that after cloning the entire script collection, the reference path remains correct.

9. Code Comments

Adding comments in scripts is a good habit.

Comments can be used to explain the written code or make notes on special treatments, so that others or yourself can quickly understand the details of the code when reviewing it later.

The level of detail in comments can be chosen reasonably based on the actual project, code, and complexity of the treatment.

Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# Date: 2022-01-01
# Author: Zhang San
#
# Find the first number within a certain range that is divisible by 2, 3, and 5

MAX_INT = 100 # Maximum search range
for i in range(MAX_INT):
    # Ignore numbers less than 2
    if i < 2:
        continue

    # Core processing
    if i % 2 == 0 and i % 3 == 0 and i % 5 == 0:
        print('First number within 100 divisible by 2, 3, and 5:', i)

        # Only need to find the first number
        break

10. Object-Oriented Programming

In the examples above, all are based on procedural programming, where the code consists entirely of functions.

Python is a multi-paradigm programming language that can be fully written procedurally but can also incorporate object-oriented techniques, making the code more concise and easier to maintain.

For simple processes, if procedural programming works well, there is no need to force the use of object-oriented techniques. This section is merely a simple demonstration of object-oriented programming development in Python.

10.1 Classes and Inheritance

A "class" refers to a collection of objects with common or similar functions and data. What a class is depends on each individual's specific implementation approach and there are no strict unified rules.

Classes can have inheritance relationships, where the inherited class is called the "parent class" and the inheriting class is called the "child class." Inheritance relationships are also written according to each individual's specific implementation approach and there are no strict unified rules.

In general:

  • The parent class writes some common methods that all child classes possess, and child classes inheriting from the parent class automatically gain all the methods of the parent class without needing to rewrite them.
  • Child classes can write additional methods that can only be called on child class objects.
  • If a method in the parent class is not applicable in the child class, the child class can rewrite the method with the same name to change its behavior in the child class objects.

10.2 Typical Example

Assume there is a "School Personnel Management System," with the following main business objects:

Personnel Description
Teacher Has a name, access card, and performs teaching activities
Student Has a name, access card, and performs learning activities

It can be seen that different personnel all have access cards, but the activities they perform differ. Thus, in specific code implementation, the access card-related functionality can be uniformly handled, while the activities need separate handling.

Example code as follows:

Python
 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class User(object):
    '''
    Base user class
    '''
    def __init__(self, name, id_card_no):
        '''
        User initialization method
        Requires passing in name and access card number
        '''
        self.name = name
        self.id_card_no = id_card_no

    def show_id_card(self):
        '''
        Display access card
        '''
        print(f'{self.name} access card number is: {self.id_card_no}')

    def do_activity(self):
        '''
        Perform activity
          Since different types of users perform different activities, there is no specific implementation here, and an error is directly raised
        '''
        raise NotImplemented()

class Teacher(User):
    '''
    Teacher class
      Inherits from the base user class
    '''

    # There is no need to rewrite the access card-related code here

    def do_activity(self):
        '''
        Perform teaching activity
          Overwrites the `do_activity` method in the parent class `User`
          When calling `do_activity` on a teacher object, this method is executed instead of the parent class method
        '''
        print(f'{self.name} teacher starts teaching students')

class Student(User):
    '''
    Student class
      Inherits from the base user class
    '''

    # There is no need to rewrite the access card-related code here

    def do_activity(self):
        '''
        Perform learning activity
          Overwrites the `do_activity` method in the parent class `User`
          When calling `do_activity` on a student object, this method is executed instead of the parent class method
        '''
        print(f'{self.name} student has entered the classroom to start studying')

zhang_hua = Teacher(name='Zhang Hua', id_card_no='T-001') # Instantiate the teacher class
li_ming   = Student(name='Li Ming', id_card_no='S-088') # Instantiate the student class

# Place all people in the same list and execute sequentially
users = [ zhang_hua, li_ming ]
for u in users:
    u.show_id_card()
    u.do_activity()

Output:

Text Output
1
2
3
4
Zhang Hua access card number is: T-001
Zhang Hua teacher starts teaching students
Li Ming access card number is: S-088
Li Ming student has entered the classroom to start studying

11. Error Handling

For some uncertain places that may cause problems (such as calling interfaces from other systems), errors during code execution may cause the entire program to crash, as follows:

Python
1
2
3
4
5
6
7
8
def get_data():
    '''
    A function that generates a division-by-zero error
    '''
    return 100 / 0

data = get_data()
print(f'Obtained data: {data}')

Output:

Text Output
1
2
3
4
5
6
Traceback (most recent call last):
  File "python-study.py", line 7, in <module>
    data = get_data()
  File "python-study.py", line 5, in get_data
    return 100 / 0
ZeroDivisionError: division by zero

At this point, we need to handle potentially problematic code separately.

Since program crashes themselves output useful error information, it is not necessary to handle every piece of code for errors. This is merely a simple demonstration of Python error handling.

11.1 Error Handling with try-except Syntax

You can use try...except to handle possible errors, as follows:

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def get_data():
    '''
    A function that generates a division-by-zero error
    '''
    return 100 / 0

try:
    # Code block that may have issues
    data = get_data()
    print(f'Obtained data: {data}')

except Exception as e:
    # Code block to handle errors
    print('Unable to obtain data')
    print(f'Error message: {e}')

Output:

Text Output
1
2
Unable to obtain data
Error message: division by zero

11.2 Raising Errors with raise Statement

When writing your own code, if you encounter non-standard input parameters, you can also manually throw errors, as follows:

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
def plus(a, b):
    if a is None or b is None:
        raise Exception('a or b is null, unable to add')
    return a + b

# Attempt to add 100 and None
try:
    result = plus(100, None)
    print(result)
except Exception as e:
    print(e)

# Attempt to add 100 and 200
try:
    result = plus(100, 200)
    print(result)
except Exception as e:
    print(e)

Output:

Text Output
1
2
a or b is null, unable to add
300