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 assigned directly, as follows:

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

2. Output Variables

There are multiple ways to output variable contents, as follows:

2.1 Using the print() Method

The print() method outputs the content of a variable directly, 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 a 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 numbers.

2.4 Output Multiple Values

print() can output multiple variable values at once, making it convenient to display 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

It is also possible to use the format "title, content" for output, which makes it easier 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

In Python, the following basic data types are included:

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 also a value used to indicate "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 Integer int, Float 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)       # Integer division
print('a %  b       Result:', a % b)        # Modulo
print('int(a / b)   Result:', int(a / b))   # Truncate integer
print('round(a / b) Result:', round(a / b)) # Round off
print('a == b       Result:', a == b)       # Equals
print('a != b       Result:', a != b)       # Not equals
print('a > b        Result:', a > b)        # Greater than
print('a >= b       Result:', a >= b)       # Greater than or equal to
print('a < b        Result:', a < b)        # Less than or equal to
print('a <= b       Result:', a <= b)       # Less than or equal to

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 concatenate strings, format them, compare equality/size (i.e., letter ordering), and check inclusion, 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)    # Size comparison
print('a < b  Result:', a < b)    # Size comparison
print('a == b Result:', a < b)    # Equality comparison
print('a in c Result:', a in c)   # Inclusion comparison

print('Use single quotes for strings                :', '"abc"')
print('Use double quotes for strings                :', "'abc'")
print('Use three single quotes for strings            :', '''abc''')
print('Use three double quotes for strings            :', """abc""")
print('Use three single/double quotes to allow multiline strings:', """
123
abc
xyz
""")
print('Use escape character \ to represent special symbols:', '\'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
Use single quotes for strings                : "abc"
Use double quotes for strings                : 'abc'
Use three single quotes for strings            : abc
Use three double quotes for strings            : abc
Use three single/double quotes to allow multiline strings:
123
abc
xyz

Use escape character \ to represent special symbols: 'abc'

Generally, it is recommended to use formatting to generate strings (in Python called f-string), as this makes the code more intuitive compared to simple concatenation.

The f-string syntax structure 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

Besides basic data types, Python also includes some very commonly used 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 a Python list can be of any type and do not require 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]

Commonly supported list operations 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]

# Add element
l.append(4)
print('After adding an element:', l)

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

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

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

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

# Get elements by index range
# Rule is according to [start index:end index], including start index but excluding end index
print('Get second element to the last:', l[1:])
print('Get second to fourth elements:', l[1:4])
print('Get second-to-last to last elements:', l[-2:])

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

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

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

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

# Get number of list elements
print('Number of list elements:', len(l))

# Sort
# Note: Cannot sort mixed lists of 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 an element: [3, 2, 1, 4]
Popped element: 4
After popping an element: [3, 2, 1]
After merging lists: [3, 2, 1, 7, 8, 9]
Get first element: 3
Get last element: 9
Get second element to the last: [2, 1, 7, 8, 9]
Get second to fourth elements: [2, 1, 7]
Get second-to-last to last elements: [8, 9]
After modifying an element: ['Hello, World!', 2, 1, 7, 8, 9]
Loop through elements:
    Value = Hello, World!
    Value = 2
    Value = 1
    Value = 7
    Value = 8
    Value = 9
Loop through elements with index:
    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 list elements: 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 a Python tuple can be of any type and do not require 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 representing tuples might confuse with ordinary parentheses, when defining a tuple with only one element, an extra comma must be added, 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 Map in other programming languages.

In Python dictionaries, Keys are generally strings, while Values can be of any type and do not require 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}

Commonly supported dictionary operations 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}

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

# Pop element
x = d.pop('b')
print('Popped element:', x)
print('After popping an element:', d)

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

# Get element
print('Get element with Key a:', d['a'])

# Get element, return None if it does not exist
print('Get element with Key xxx, return None if it does not exist:', d.get('xxx'))

# Get element, return default value if it does not exist
print('Get element with Key xxx, return default value if it does not exist:', d.get('xxx', 'Default'))

# Get list of Keys
print('Get list of Keys:', list(d.keys()))

# Get list of Values
print('Get list of Values:', list(d.values()))

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

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

# Get number of dictionary elements
print('Number of dictionary elements:', 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 popping an element: {'a': 1}
After merging dictionaries: {'a': 1, 'x': 9}
Get element with Key a: 1
Get element with Key xxx, return None if it does not exist: None
Get element with Key xxx, return default value if it does not exist: Default
Get list of Keys: ['a', 'x']
Get list of Values: [1, 9]
After modifying an element: {'a': 'Hello, World!', 'x': 9}
Loop through elements:
    Key = a , Value = Hello, World!
    Key = x , Value = 9
Number of dictionary elements: 2

4.4 Sets set

Sets are unordered collections of unique elements.

Elements in a Python set can be of any type and do not require 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'}

Commonly supported set operations 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'}

# Add element
s.add(3)
print('After adding an element:', s)

# Remove element
s.remove('a')
print('After removing an element:', s)

# Intersection of sets
print('Intersection of sets:', s & {2, 3, 4})
# Union of sets
print('Union of sets:', s | {7, 8, 9})
# Difference of sets
print('Difference of sets:', s - {1, 2})

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

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

# Get number of set elements
print('Number of set elements:', len(s))

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

Output:

Text Output
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
After adding an element: {3, 1, 2, 'a'}
After removing an element: {3, 1, 2}
Intersection of sets: {2, 3}
Union of sets: {1, 2, 3, 7, 8, 9}
Difference of sets: {3}
Convert to list: [3, 1, 2]
Loop through elements:
    Value = 3
    Value = 1
    Value = 2
Number of set elements: 3
Remove 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 composed of basic data types, lists, tuples, and dictionaries can be converted into 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 here
    }
]
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, use if ... elif ... else for conditional handling, 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 achieve more complex control, 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, you can use for ... or while ... for loop handling.

6.1 for Loop

for loops are generally used for known iteration counts, such as traversing lists, like:

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, such as:

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 loop through lists and simultaneously obtain indices, such as:

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

Output:

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

6.2 while Loop

while loops are generally used for known conditions, executing the loop while the condition is met and ending it when the condition is no longer satisfied, such as:

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

Be cautious when using while loops, ensuring that the condition eventually becomes false to prevent infinite loops.

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, such as:

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 code segments 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 above example, the plus function contains a and b as two parameters for input. These input parameters can be directly used within the function.

Additionally, function parameters support default values. Parameters with default values do not need to be specified during function calls, such as:

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 adhering to the order, such as:

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 function results. Besides returning a single value, functions can also return multiple values at once, such as:

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('Receiving with a single variable:', result)

is_ok, result = check_score(80)
print('Receiving with corresponding number of variables:', is_ok, result)

Output:

Text Output
1
2
Receiving with a single variable: (True, 'Excellent')
Receiving with corresponding number of variables: True Good

8. Import Modules with import Statement

In more complex projects, it is often necessary to place code in multiple different scripts for easier maintenance and management.

When calling code between scripts, the import statement is required.

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

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

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, alias as b
from a import hello2, hello3 # From a, import hello2, hello3

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 and most common part. For complete and detailed import introduction, please refer to professional tutorials.

8.1 Scripts in DataFlux Func

Due to the special mechanism of script management in DataFlux Func, scripts in the system are not stored as files but saved in the database. Therefore, importing other scripts in DataFlux Func differs somewhat from standard Python.

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

Script sets and scripts each have their own ID and are associated. The ID of a script under a certain script set is always {associated script set ID}__{script name} (with two underscores in between), as shown in the figure below:

8.2 Importing Scripts in DataFlux Func

Assume the following script sets and scripts exist:

Then, the import methods are as follows:

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

For Python scripts in the same script set, it is recommended to use import __{script name} to ensure the reference path remains correct after cloning the entire script set.

9. Code Comments

Adding comments in scripts is a good habit.

Comments can be used to explain the written code or annotate special treatments, allowing others or yourself to 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. It can be fully written procedurally, but it can also incorporate object-oriented techniques, making the code more concise and easier to maintain.

For simple treatments, procedural programming can suffice without forcing the use of object-oriented techniques. This is merely a simple demonstration of object-oriented programming in Python.

10.1 Classes and Inheritance

A "class" refers to a collection of objects with common or similar functionalities and data. What a class represents mainly depends on the individual's specific implementation approach, with 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 similarly written based on the individual's specific implementation approach, with no strict unified rules.

Generally speaking:

  • The parent class writes some common methods possessed by all child classes. Child classes inheriting from the parent class do not need to rewrite these methods and automatically gain all methods from the parent class.
  • Child classes can write additional methods, which can only be invoked on child class objects.
  • If a method in the parent class is not applicable to the child class, the child class can rewrite the method with the same name to change its behavior when invoked on child class objects.

10.2 Typical Example

Suppose there is a "school personnel management system," with the following main business objects:

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

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

Sample code is 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):
        '''
        Show access card
        '''
        print(f'{self.name} access card number is: {self.id_card_no}')

    def do_activity(self):
        '''
        Conduct activity
          Since different types of users conduct different activities, there is no specific implementation here, so an error is raised
        '''
        raise NotImplemented()

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

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

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

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

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

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

zhang_hua = Teacher(name='Zhang Hua', id_card_no='T-001') # Instantiate teacher class
li_ming   = Student(name='Li Ming', id_card_no='S-088') # Instantiate 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 enters the classroom to start studying

11. Error Handling

For uncertain places where problems may occur (such as calling interfaces from other systems), the program may crash if errors occur during execution, such as:

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

data = get_data()
print(f'Obtained data is {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 messages, it is not mandatory to handle every piece of code for errors. This is just a simple demonstration of Python error handling.

11.1 Error Handling with try-except Syntax

You can use try...except to handle potential errors, such as:

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

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

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

Output:

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

11.2 Throwing Errors with raise Statement

When writing your own code, if encountering non-conforming input parameters, you can also actively throw errors, such as:

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 empty, 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 empty, unable to add
300