0% found this document useful (0 votes)
2 views

02 Python Lab Guide-Student Version

The document is a Python Lab Guide from Huawei Technologies, detailing various experiments and procedures related to Python programming. It covers topics such as data types, control loops, function customization, object-oriented programming, and standard library usage. Each section includes specific examples and code snippets to illustrate the concepts being taught.

Uploaded by

kenneth kwanshe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

02 Python Lab Guide-Student Version

The document is a Python Lab Guide from Huawei Technologies, detailing various experiments and procedures related to Python programming. It covers topics such as data types, control loops, function customization, object-oriented programming, and standard library usage. Each section includes specific examples and code snippets to illustrate the concepts being taught.

Uploaded by

kenneth kwanshe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Artificial Intelligence Technology and Application

Python
Lab Guide
Teacher Version

HUAWEI TECHNOLOGIES CO., LTD.

1
Contents

1 Data Type Experiment ........................................................................................................... 1


1.1 Procedure .................................................................................................................................................................................... 1
1.1.1 Hello world .............................................................................................................................................................................. 1
1.1.2 Data Type: Number .............................................................................................................................................................. 1
1.1.3 Data Type: String .................................................................................................................................................................. 1
1.1.4 Data Type: List ....................................................................................................................................................................... 2
1.1.5 Data Type: Tuple ................................................................................................................................................................... 3
1.1.6 Data Type: Dictionary .......................................................................................................................................................... 4
1.1.7 Data Type: Set ........................................................................................................................................................................ 4
2 Control Loop Experiment ...................................................................................................... 6
2.1 Procedure .................................................................................................................................................................................... 6
2.1.1 Deep Copy and Shallow Copy .......................................................................................................................................... 6
2.1.2 if Statement ............................................................................................................................................................................ 6
2.1.3 Loop Statement ..................................................................................................................................................................... 7
3 Function and Object-oriented Experiment ....................................................................... 9
3.1 Procedure .................................................................................................................................................................................... 9
3.1.1 Function Customization ...................................................................................................................................................... 9
3.1.2 Object Orientation ..............................................................................................................................................................10
4 Standard Library Usage.......................................................................................................12
4.1 Procedure ..................................................................................................................................................................................12
4.1.1 Standard Library Usage ....................................................................................................................................................12
5 Database Programming ......................................................................................................16
5.1 Database Programming .......................................................................................................................................................16
5.1.1 Installing the Database .....................................................................................................................................................16
5.2 Creating a database ..............................................................................................................................................................22
5.3 Database Programming .......................................................................................................................................................22
6 I/O Operation Experiment ..................................................................................................25
6.1 Procedure ..................................................................................................................................................................................25
6.1.1 I/O Operations .....................................................................................................................................................................25
7 Regular Expression Experiment.........................................................................................27
7.1 Introduction ..............................................................................................................................................................................27
7.1.1 Regular Expressions ...........................................................................................................................................................27
8 Generators, Iterators, and Decorators .............................................................................30
8.1 Procedure ..................................................................................................................................................................................30
8.1.1 Iterator ....................................................................................................................................................................................30
8.1.2 Generators .............................................................................................................................................................................30
8.1.3 Decorators .............................................................................................................................................................................31
9 Treasury Management System..........................................................................................33
9.1 Introduction ..............................................................................................................................................................................33
9.1.1 About This Lab .....................................................................................................................................................................33
9.1.2 Objectives ..............................................................................................................................................................................33
9.2 Procedure ..................................................................................................................................................................................33
9.2.1 Experiment Approach ........................................................................................................................................................33
9.2.2 Implementation ...................................................................................................................................................................33
Python Lab Guide-Student Version Page 1

1 Data Type Experiment

1.1 Procedure
1.1.1 Hello world
The first Python program generates "hello world".

# Generate "hello world".

# Generate "hello world". The output is the same when single and double quotation marks are
carried in input.

1.1.2 Data Type: Number


You need to be familiar with the basic operations of numbers in Python. Note that Boolean
operations in Python use the keyword and/or/not instead of the operator.

# The output is 1. By default, True indicates 1, and False indicates 0.

# If True is displayed, enter "or" or perform the OR operation.

# The output is 2, and // is the rounding operator.

# The output is 1, and % is the modulo operator.

# The output is 9, and ** indicates the power operation.

# The output is 6.6. By default, the sum of numbers of different precisions is the number of the
highest precision type.

1.1.3 Data Type: String


Step 1 Basic operations on strings:

# Assign value "python" to variable S.

# len(obj): Return the object length.


# Output: 6

# The output is pyn. Elements are obtained by index.


Python Lab Guide-Student Version Page 2

# The output is python1 pythonpython, which indicates mergence and duplication.

Step 2 Immutability of strings:

# Assign value "python" to variable S.

# The program is abnormal.

# New string Zython is generated and assigned to S1.

# Output: S:python, S1:Zython

Step 3 Common operations on strings:

# Assign value "python" to variable S.

# str.split(str="", num=-1): The string is split by separator. If the num parameter has a value, divide
the string into num+1 substrings. The value -1 indicates that all strings are split.

# The output is ['pyt','on']. The string is split by h.

# str.replace(old, new[, max]): A string generated after the old string is replaced with the new string
is returned. If the third parameter max is specified, the number of times that the old string is replaced
with the new string cannot exceed the value of max.
# In the string, py is replaced with PY.

# str.upper(): Return the value after lowercase letters are converted to uppercase letters.
# PYTHON

# str.lower(): Return the value after uppercase letters are converted to lowercase letters.
# The output is python because all uppercase letters are converted to lowercase letters.

# \n is a newline character.

# str.join(sequence): sequence indicates a sequence to be joined. In the output, the new string
generated after the elements in the specified character join sequence is returned.
# The output is life is short. The join function is used for concatenating strings.

# Format the string.

# Output: hello world 12

1.1.4 Data Type: List


Common operations on lists:

animals = ['cat', 'dog', 'monkey']


# list.append(obj): Add a new object to the end of the list.
# Append an element.
Python Lab Guide-Student Version Page 3

# Output: ['cat', 'dog', 'monkey', ‘fish’]

# list.remove(obj): Remove the first match for a value in the list.


# Delete element fish.

# Output: ['cat', 'dog', 'monkey']

# list.insert(index, obj): Insert a specified object to a specified position in the list. The index indicates
the position.
# Insert element fish at subscript 1.

# Output: ['cat', ‘fish’, 'dog', 'monkey']

# list.pop([index=-1]): Remove the element (the last element by default) corresponding to the
subscript in the list. The index indicates the subscript.
# Delete the element whose subscript is 1.

# Output: ['cat', 'dog', 'monkey']

# Traverse and obtain the elements and indexes.


# enumerate(sequence): Return an index sequence consisting of a data object that can be traversed
and list the data and subscripts. This function is usually used in the for loop.
# Index consisting of the element subscript and element

Output: (0, cat)


(1, dog)
(2, monkey)
# List derivation.
# Generate a list of elements that comply with rules in batches.

#['catcat ', 'dogdog ', 'monkeymonkey ']

# list.sort(cmp=None, key=None, reverse=False): The cmp parameter is an optional parameter. If this


parameter is specified, the method uses this parameter is used for sorting. Key is an element used for
comparison. reverse indicates the sorting rule, and False indicates the ascending order.
# Sort the list.

# Output: [12,32,45,55]

# list.reverse(): Element in the reverse list.


# Reverse the list.

# Output: [55,45,32,12]

1.1.5 Data Type: Tuple


Common operations on tuples:

# Create a tuple.

#Tuples are combined. The output is (1, 2, 3, 4, 5).


Python Lab Guide-Student Version Page 4

# A tuple with only one element, which is different from a number.

# Create a tuple.

# The program is abnormal, and the tuple is unchangeable.

# Elements that can be changed in a tuple are changeable.

# (12,45,32,55,[2,0,3])

1.1.6 Data Type: Dictionary


Common operations on dictionaries:

# Three value assignment operations on dictionaries.

# dict.copy(): Copy data.

# {'food':'Spam','quantity':4,'color':'pink'}

# {'food':'Spam','quantity':4,'color':'red'}

# Element access.
# Obtain the error information.

# Output: None

# Output: The key value does not exist.

# Output: dict_keys(['food', 'quantity', 'color'])

# Output: dict_values(['Spam', 4, 'red'])

# Output: dict_items([('food', 'Spam'), ('quantity', 4), ('color', 'red')])


# Clear all data in the dictionary.

# Output: {}

# Delete the dictionary.

# The program is abnormal, and a message is displayed, indicating that d is not defined.

1.1.7 Data Type: Set


Common operations on sets:

sample_set = {'Prince', 'Techs'}


# The output is False. in is used to check whether an element exists in the set.
Python Lab Guide-Student Version Page 5

# set.add(obj): Add an element to a set. If the element to be added already exists in the set, no
operation is performed.
# Add element Data to the set.

# Output: {'Prince', 'Techs', 'Data'}

# Output: 3

# set.remove(obj): Remove a specified element from a set.


# Delete element Data.

# {'Prince', 'Techs'}

list2 = [1,3,1,5,3]
# The output is [1,3,5]. The uniqueness of the set elements is used to deduplicate the list.

# Invariable set.
Python Lab Guide-Student Version Page 6

2 Control Loop Experiment

2.1 Procedure
2.1.1 Deep Copy and Shallow Copy
The copy module in Python is used to implement deep copy.

import copy
# Create a dictionary.

# Shallow copy.

# Deep copy.

# Change the value of the nested list in the original data.

Output:

Dict1:{‘name’:’lee’, ‘age’:89, ‘num’:[1,6,8]}


# The shallow copy data is modified.

# The deep copy data is not modified.

2.1.2 if Statement
You can use the if statement in Python to determine the level of a score input by a user.

# Determine the entered score.


# input(): Receive input data.

# The input function receives input, which is a string.

# Convert the score to a number.


# try: except Exception: … is a Python statement used to capture exceptions. If an error occurs in
the statement in try, the statement in except is executed.
Python Lab Guide-Student Version Page 7

# Check whether the entered value is greater than the score of a level.

# Generate the level when conditions are met.

2.1.3 Loop Statement


Step 1 for loop
Use the for loop to generate a multiplication table.

# Define the outer loop.

# Define the inner loop.

# Format the output string to align the generated result. The end attribute is set to /n by default.

Output:

1*1= 1
2*1= 2 2*2= 4
3*1= 3 3*2= 6 3*3= 9
4*1= 4 4*2= 8 4*3=12 4*4=16
5*1= 5 5*2=10 5*3=15 5*4=20 5*5=25
6*1= 6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36
7*1= 7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49
8*1= 8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64
9*1= 9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81

Step 2 while loop


When the condition is met, the statement block is executed cyclically. To end the loop, use
break or continue.

# while loop
# Create the variable i.

# Set a condition for the loop.

# The value of i increases by 1 in each loop.

# Check whether the conditions are met.

# Execute continue to exit the current loop.


Python Lab Guide-Student Version Page 8

# Exit the current big loop.

Output

1
2
Exit the current loop.
4
Exit the current big loop.
Python Lab Guide-Student Version Page 9

3 Function and Object-oriented


Experiment

3.1 Procedure
3.1.1 Function Customization
Step 1 Define a function.

Define a function to return a sequence. Each number in the sequence is the sum of the
former two numbers (Fibonacci sequence).

# Position parameter.

# Create a list to store the sequence value.

# Cycle num-2 times.

# Append the value to the list.

# Return the list.

Output:

[0, 1, 1, 2, 3]

Step 2 Generate parameters.

The function can be customized to generate parameters transferred in different ways.

# Default parameters.

# Format the output.

# hello,world Default parameter.

# Greetings,world Position parameter.


Python Lab Guide-Student Version Page 10

# Greetings, universe Position parameter.

# hello, Gumby Keyword parameter.

Output:

hello, world!
Greetings, world!
Greetings, universe!
hello, Gumby!

3.1.2 Object Orientation


Step 1 Create and use classes.

Create the Dog class.


Each instance created based on the Dog class stores the name and age. We will give each
dog the sit () and roll_over () abilities.

class Dog():
"""A simple attempt to simulate a dog"""

"""Initialize the name and age attributes."""

"""Simulate a dog sitting when ordered."""

"""Simulate a dog rolling over when ordered."""

Output:

Husky is now sitting


Husky rolled over!

Step 2 Access attributes.

class Employee:

# Create the first object of the Employee class.

# Create the second object of the Employee class.


Python Lab Guide-Student Version Page 11

Output:

Name : Zara ,Salary: 2000


Name : Manni ,Salary: 5000
Total Employee 2

Step 3 Inherit a class.

One of the main benefits of object-oriented programming is code reuse, which is achieved
through inheritance. Inheritance can be understood as the type and subtype relationships
between classes.

class Parent: # Define the parent class.

# Instantiate a child class.

# Invoke the method of a child class.

# Invoke the method of a parent class.

# Invoke the method of the parent class again to set the attribute value.

# Invoke the method of the parent class again to obtain the attribute value.

Output:

Invoke a child class to construct a method.


Invoke the method of a child class.
Invoke the method of a parent class.
Parent attribute: 200

Step 4 Class attributes and methods.

class JustCounter:

# An error is reported, indicating that the instance cannot access private variables.

Output:

1
2
2
Python Lab Guide-Student Version Page 12

4 Standard Library Usage

4.1 Procedure
4.1.1 Standard Library Usage
Step 1 sys
sys.exit([n]): This method can be used to exit the current program. If the value of n is 0,
the program exits normally; if the value of n is not 0, the program exits abnormally.

import sys

Output:

0
1
2
3
4
5
An exception has occurred, use %tb to see the full traceback.

sys.path: returns the search paths of Python modules.

Output:

['D:\\python3.6\\python36.zip',
'D:\\python3.6\\DLLs',
'D:\\python3.6\\lib',
'D:\\python3.6',
'',
'D:\\python3.6\\lib\\site-packages',
'D:\\python3.6\\lib\\site-packages\\IPython\\extensions',
'C:\\Users\\xxx\\.ipython']

sys.platform: returns the system running platform.


Python Lab Guide-Student Version Page 13

Output:

'win32'

sys.argv: transfers parameters from outside of the program to the program. The
parameters are transferred in list format. The first parameter is the current file name.
Create the .py file test.py (in the current folder or on the desktop) and write the following
code:

Switch to the file path in the command line and run the program.

Output:

Figure 4-1 Receiving parameters from outside


Step 2 os

import os
# os.getpid() Obtain the current process ID.

# os.getppid(): Obtain the ID of the current parent process.

# os.getcwd(): Obtain the current path.

# os.chdir(path): Change the current working directory.

# os.listdir(): Return all files in the directory.

# os.walk(): Export all files in the current path.

Output:
Python Lab Guide-Student Version Page 14

Figure 4-2 Execution result of the OS module


os.path module: obtains file attributes.

import os
# os.path.abspath(path): Return the absolute path.

# os.path.exists(path): If the file exists, True is returned; if the file does not exist, False is returned.

# os.path.getsize(path): Return the file size. If the file does not exist, an error is returned.

# os.path.isfile(path): Check whether the path is a file.

# os.path.isdir(path): Check whether the path is a folder.

Output:

The absolute path of text.txt is D:\python project\text.txt


Whether text.txt exists: True
Size of the text.txt file: 0
Whether text.txt is a file: True
Whether text.txt is a folder: False

Step 3 time

import time
# time.time(): Obtain the current timestamp.

# time.localtime(): Obtain the time tuple.

# time.asctime(): Obtain formatted time.

#time.strftime(format[, t]): Receive the time tuple and return the local time expressed in a readable
string, in the format specified by the format parameter.
Python Lab Guide-Student Version Page 15

Output:

Timestamp: 1555950340.4777014
Local time: time.struct_time(tm_year=2019, tm_mon=4, tm_mday=23, tm_hour=0, tm_min=25,
tm_sec=40, tm_wday=1, tm_yday=113, tm_isdst=0)
Local time: Tue Apr 23 00:25:40 2019
2019-04-23 00:25:40
Python Lab Guide-Student Version Page 16

5 Database Programming

5.1 Database Programming


5.1.1 Installing the Database
Step 1 Download the installation package from the official website
https://www.mysql.com/

Choose DOWNLOADS to go to the Download page


Python Lab Guide-Student Version Page 17

After that, select the MySQL Community Server at the bottom of the page

So here you can choose your own version (Windows,Linux,Mac) according to your
operating system. Here we Windows as a display
Python Lab Guide-Student Version Page 18

Click Download after selecting the system

Here they want us to register an account, but we don't have to choose the following No
thanks just start my download
Python Lab Guide-Student Version Page 19

After the download is complete, decompress the ZIP package to a directory.


Open the decompressed file, create the my.ini configuration file in the folder, and edit the
my.ini configuration file to configure the following basic information:

[mysql]
# Set the default character set of the MySQL client.

[mysqld]
# Set the port 3306.

# Set the MySQL installation directory. Replace ## with the installation directory.

# Set the directory for storing the MySQL database data.


# datadir=##
# Maximum number of connections allowed.

# The default character set used by the server is the 8-bit latin1 character set.

# Default storage engine used when a new table is created.

Step 2
Step 3 Start MySQL.
Open the CLI as the administrator, switch to the decompressed folder, and go to the bin
directory.

After initialization, you obtain a random password in the following format:


root@localhost:Random password.
Run the following command to install the MySQL:

Start the MySQL database.

Log in to the MySQL database.

Change the password.

Step 4 Configure environment variables.


Python Lab Guide-Student Version Page 20

Right-click My Computer, choose Properties from the shortcut menu, and select
Advanced system settings.

Figure 5-1 System Properties


Click Environment Variables. Add the database path to the path variable.
Python Lab Guide-Student Version Page 21
Python Lab Guide-Student Version Page 22

Figure 5-2 Configure environment variables.

5.2 Creating a database


Create database my_database.

Figure 5-3 Creating a database


Switch the database.

Figure 5-4 Switching the database

5.3 Database Programming


Step 1 Install modules required for the database.
Run the pip command to install a third-party library in Python.

Step 2 Connect to the database.

import pymysql
# Connect to the database.

# localhost: local connection. You can also change it to the IP address of the database.
# root: MySQL database account; mysql: database password.
# my_database: name of the database to be connected.
# Use the cursor() method to obtain the operation cursor.

# Execute the SQL statement using the execute method.

# Use the fetchone() method to obtain a data record.

Output:

Database version : 8.0.15


Python Lab Guide-Student Version Page 23

Step 3 Use Python to operate the database.

import pymysql
# Connect to the database.

# Use the cursor() method to obtain the operation cursor.

# SQL statement for creating a data table.

# Run the following commands:

# Close the database connection.

Check the result in the MySQL database.

Figure 5-5 Checking the MySQL database


Step 4 Data operations
Insert data.

import pymysql

# Connect to the database.

# Use the cursor() method to obtain the operation cursor.

# Execute the SQL INSERT statement.

# You only need to modify the SQL statement to be executed to delete or modify the data.

# Execute the SQL statement.

# Submit data to the database for execution.

# Rollback upon an error.

# Close the database connection.


Python Lab Guide-Student Version Page 24

View the result in the database.

Figure 5-6 Viewing the inserted data


Python Lab Guide-Student Version Page 25

6 I/O Operation Experiment

6.1 Procedure
6.1.1 I/O Operations
Step 1 Write data to a file.

f = open("text.txt", 'w') # Open the text.txt file. If the file does not exist, a new file will be

Output

Figure 6-1 Content to be written

Figure 6-2 File content

Step 2 Read file data.

f = open("text.txt", 'r')
# Read six characters and move the cursor six characters backward.

# Read from the current position of the cursor to the end.

Output

python
Operation
Python Lab Guide-Student Version Page 26

Step 3 Use the context manager to operate the file.

# Use the with statement to write file data.

# Use the with statement to read the file content.

Output

Python file operation

Step 4 Use the OS module to operate the file.

import os
# Rename the file.

# Delete the file.


Python Lab Guide-Student Version Page 27

7 Regular Expression Experiment

7.1 Introduction
7.1.1 Regular Expressions
Step 1 re.match function
The re.match function attempts to match a pattern from the start position of the string. If
the match is not successful, match() returns none.
Function syntax:

Example:

import re
# Match at the start position.

# Not match at the start position.

Output:

(0, 3)
None

Step 2 re.search method


The re.search method scans the entire string and returns the first successful match.
Function syntax:

Example:

import re
Python Lab Guide-Student Version Page 28

Output:

searchObj.group() : Cats are smarter than dogs


searchObj.group(1) : Cats
searchObj.group(2) : smarter

Step 3 Retrieval and replacement


The re module of Python provides re.sub function to replace the matching items in the
string.
Syntax:

Example:

import re
phone = "2019-0101-000 # This is a phone number."
# Delete the Python comment in the string.

# Delete the hyphens from the phone number.

Output:

Phone number: 2019-0101-000


Phone number: 20190101000

Step 4 re.compile function


The compile function is used to compile regular expressions and generate a regular
expression object (pattern) for the match() and search() functions.
The syntax format is as follows:

Example:

import re
# At least one digit is matched.

# The header is not found.

Output:
Python Lab Guide-Student Version Page 29

None
<_sre.SRE_Match object; span=(3, 5), match='12'>
12

Step 5 re.split()
The split method splits a string based on the matched substring and returns a list. The
usage of the method is as follows:

Example:

import re
s = re.split('\W+', 'www.huawei.com')
print(s)

Output:

['www', 'huawei', 'com']


Python Lab Guide-Student Version Page 30

8 Generators, Iterators, and Decorators

8.1 Procedure
8.1.1 Iterator
Step 1 Determine an iterable object.

# Use the isinstance() method to determine whether an object can be iterated.


# Iterable object.

Output:

True
True
False

Step 2 Obtain the iterator.


The iter() function is used to obtain the iterators of the iterable objects. You can use the
next() function continuously for the obtained iterator to obtain the next data record.

l = [1, 2, 3, 4, 5]

Output:

False
True

8.1.2 Generators
Step 1 Create a generator through list derivation.
Python Lab Guide-Student Version Page 31

Output:

<class 'generator'>

Step 2 Create a generator through a yield keyword.


Use the yield keyword to create a generator to generate the Fibonacci sequence.

Output:

value:0
value:1
value:1
value:2
value:3
Generator return value: done

Step 3 Use the send method.


In addition to the next method, the send method can be used to wake up the generator.
Compared with the next method, the send method can also transfer data to the breakpoint
when waking up the generator.

>>>0
f.send('haha')
>>>haha
>>>1
next(f)
>>>None
>>>2

8.1.3 Decorators
Step 1 Construct a decorator.
Create a simple decorator that calculates the runtime of a function.

import time
Python Lab Guide-Student Version Page 32

Step 2 Use the decoration function.

@func
def test():

Output:

Time consumed: 2.000276803970337 seconds


Python Lab Guide-Student Version Page 33

9 Treasury Management System

9.1 Introduction
9.1.1 About This Lab
Python is used to implement a treasury management system, which provides deposit,
withdrawal, transfer, secret management, and credential generation functions. Data is
stored in the MySQL database.

9.1.2 Objectives
For the comprehensive application of Python basic syntax and advanced syntax, a simple
treasury management system is implemented.

9.2 Procedure
9.2.1 Experiment Approach
Use the PyMySql to connect to and operate the database, and log in to the database to
determine the information in the database. After the login is successful, the system
welcome page is displayed. In addition, a user object is created for the user who logs in
successfully. The corresponding method is performed according to the operation performed
by the user, and the operation is synchronized to the database. After the operation is
complete, the operation is recorded, that is, the operation is written to a local file.

9.2.2 Implementation
Step 1 Create a database and data table.
Create a database.

Create a data table.


Python Lab Guide-Student Version Page 34

Insert data.

Considering that the system connects to the database for many times and the statements
for connecting to the database are similar, the database connection is encapsulated as a
method.

# Define the method of connecting to the database. The SQL statement is the database operation
statement to be executed each time.
def con_mysql(sql):

Test method:

sql = "select * from user"


con_mysql(sql)

Output:

Figure 9-1 Database connection test result


Step 2 Define a user class.

class Account(object):
Python Lab Guide-Student Version Page 35

# Account balance.

# User name.

# Last login time.

# Deposit.
def save(self):

# Withdrawal.
def take(self):

# Change the password.


def update(self):

# Transfer.
def transfer(self):

# Perform the selected operation.

# Generate the credential after the operation.


def voucher(self,end_time, action):

Login function

Test the login function:

user_account = login()
user_account

Output:
Python Lab Guide-Student Version Page 36

Figure 9-2 Login function test


Step 3 Welcome window

def welcome():

Test the welcome method:

action = welcome()
action

Output:

Figure 9-3 Welcome window


Step 4 Define the system startup function.
Configure the startup function.

def run():

Define the decorator.

def consume_time(func, *args, **kwargs):


def inner(*args, **kwargs):

Add the following function to the system startup function:

@consume_time
def run():
Python Lab Guide-Student Version Page 37

Output:

Figure 9-4 System execution result

Figure 9-5 Generated credential

You might also like