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

02 Python Lab Guide-Student Version

Uploaded by

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

02 Python Lab Guide-Student Version

Uploaded by

Rahmawita Getari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

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 ................................................................................................................................................ 3
1.1.7 Data Type: Set ............................................................................................................................................................ 3
2 Control Loop Experiment ......................................................................................................... 5
2.1 Procedure ..................................................................................................................................................................... 5
2.1.1 Deep Copy and Shallow Copy .................................................................................................................................... 5
2.1.2 if Statement ............................................................................................................................................................... 5
2.1.3 Loop Statement ......................................................................................................................................................... 6
3 Function and Object-oriented Experiment ............................................................................... 7
3.1 Procedure ..................................................................................................................................................................... 7
3.1.1 Function Customization ............................................................................................................................................. 7
3.1.2 Object Orientation ..................................................................................................................................................... 7
4 Standard Library Usage .......................................................................................................... 11
4.1 Procedure ................................................................................................................................................................... 11
4.1.1 Standard Library Usage ............................................................................................................................................ 11
5 Database Programming ......................................................................................................... 15
5.1 Database Programming .............................................................................................................................................. 15
5.1.1 Installing the Database ............................................................................................................................................ 15
5.2 Creating a database .................................................................................................................................................... 18
5.3 Database Programming .............................................................................................................................................. 19
6 I/O Operation Experiment ..................................................................................................... 21
6.1 Procedure ................................................................................................................................................................... 21
6.1.1 I/O Operations ......................................................................................................................................................... 21
7 Multitask Experiment ............................................................................................................ 23
7.1 Multiple Tasks ............................................................................................................................................................. 23
7.1.1 Multitask Programming ........................................................................................................................................... 23
8 Regular Expression Experiment .............................................................................................. 26
8.1 Introduction ................................................................................................................................................................ 26
8.1.1 Regular Expressions ................................................................................................................................................. 26
9 Generators, Iterators, and Decorators.................................................................................... 29
9.1 Procedure ................................................................................................................................................................... 29
9.1.1 Iterator ..................................................................................................................................................................... 29
9.1.2 Generators ............................................................................................................................................................... 30
9.1.3 Decorators ............................................................................................................................................................... 31
10 Treasury Management System ............................................................................................. 32
10.1 Introduction .............................................................................................................................................................. 32
10.1.1 About This Lab ....................................................................................................................................................... 32
10.1.2 Objectives .............................................................................................................................................................. 32
10.2 Procedure ................................................................................................................................................................. 32
10.2.1 Experiment Approach ............................................................................................................................................ 32
10.2.2 Implementation ..................................................................................................................................................... 32
Python Lab Guide-Teacher Version Page 1

1 Data Type Experiment

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

print('hello world') # Generate "hello world".


print("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.

print(True+False) # The output is 1. By default, True indicates 1, and False indicates 0.


print(True or False) # If True is displayed, enter "or" or perform the OR operation.
print(5//2) # The output is 2, and // is the rounding operator.
print(5%2) # The output is 1, and % is the modulo operator.
print(3**2) # The output is 9, and ** indicates the power operation.
print(5+1.6) # 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:

S = 'python' # Assign value "python" to variable S.


# len(obj): Return the object length.
print(len(S)) # Output: 6
print(S[0], S[1], S[-1]) # The output is pyn. Elements are obtained by index.
print (S+' 1', S*2) # The output is python1 pythonpython, which indicates mergence and
duplication.

Step 2 Immutability of strings:

S = 'python' # Assign value "python" to variable S.


S[0] = 'Z' # The program is abnormal.
S1 ='Z'+S[1:] # New string Zython is generated and assigned to S1.
print("S:%s, S1:%s"%(S, S1))# Output: S:python, S1:Zython

Step 3 Common operations on strings:


Python Lab Guide-Teacher Version Page 2

S = "python" # 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.
print(S.split('h')) # 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.
print(S.replace('py','PY')) # In the string, py is replaced with PY.
# str.upper(): Return the value after lowercase letters are converted to uppercase letters.
print(S.upper()) # PYTHON
# str.lower(): Return the value after uppercase letters are converted to lowercase letters.
print ('PYTHON'.lower()) # The output is python because all uppercase letters are
converted to lowercase letters.
line= 'aa,bb,ccc,dd\n' # \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.
print (' '.join([' life ',' is ',' short '])) # The output is life is short. The join function is used for
concatenating strings.
hw12= '%s %s %d' % ('hello', 'world', 12) # Format the string.
print(hw12) # 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.
animals.append ('fish') # Append an element.
print(animals) # Output: ['cat', 'dog', 'monkey', ‘fish’]
# list.remove(obj): Remove the first match for a value in the list.
animals.remove ('fish') # Delete element fish.
print(animals) # Output: ['cat', 'dog', 'monkey']
# list.insert(index, obj): Insert a specified object to a specified position in the list. The index indicates the position.
animals.insert (1, 'fish') # Insert element fish at subscript 1.
print(animals) # 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.
animals.pop(1) # Delete the element whose subscript is 1.
print(animals) # 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.
for i in enumerate(animals):
print(i) # Index consisting of the element subscript and element
Output: (0, cat)
(1, dog)
(2, monkey)
# List derivation.
squares = [x*2 for x in animals] # Generate a list of elements that comply with rules in batches.
print(squares) #['catcat ', 'dogdog ', 'monkeymonkey ']
list1 = [12,45,32,55]
# 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.
list1.sort() # Sort the list.
Python Lab Guide-Teacher Version Page 3

print(list1) # Output: [12,32,45,55]


# list.reverse(): Element in the reverse list.
list1.reverse() # Reverse the list.
print(list1) # Output: [55,45,32,12]

1.1.5 Data Type: Tuple


Common operations on tuples:

T=(1,2,3) # Create a tuple.


print(T+(4,5)) #Tuples are combined. The output is (1, 2, 3, 4, 5).
t=(42,) # A tuple with only one element, which is different from a number.
tuple1 = (12,45,32,55,[1,0,3]) # Create a tuple.
tuple1[0] = "good" # The program is abnormal, and the tuple is unchangeable.
tuple1[4][0] = 2 # Elements that can be changed in a tuple are changeable.
print(tuple1) # (12,45,32,55,[2,0,3])

1.1.6 Data Type: Dictionary


Common operations on dictionaries:

# Three value assignment operations on dictionaries.


x = {'food':'Spam','quantity':4,'color':'pink'}
X =dict(food='Spam',quantity=4, color='pink')
x = dict([("food", "Spam"),("quantity", "4"),("color","pink")])
# dict.copy(): Copy data.
d =x.copy()
d['color'] = 'red'
print(x) # {'food':'Spam','quantity':4,'color':'pink'}
print(d) # {'food':'Spam','quantity':4,'color':'red'}
# Element access.
print (d ['name']) # Obtain the error information.
print(d.get('name')) # Output: None
print(d.get('name','The key value does not exist.')) # Output: The key value does not exist.
print(d.keys()) # Output: dict_keys(['food', 'quantity', 'color'])
print(d.values()) # Output: dict_values(['Spam', 4, 'red'])
print(d.items())
# Output: dict_items([('food', 'Spam'), ('quantity', 4), ('color', 'red')])
d.clear() # Clear all data in the dictionary.
print(d) # Output: {}
del(d) # Delete the dictionary.
print(d) # 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'}


print('Data' in sample_set) # The output is False. in is used to check whether an element exists in the
set.
# set.add(obj): Add an element to a set. If the element to be added already exists in the set, no operation is
performed.
sample_set.add('Data') # Add element Data to the set.
print(sample_set) # Output: {'Prince', 'Techs', 'Data'}
Python Lab Guide-Teacher Version Page 4

print(len(sample_set)) # Output: 3
# set.remove(obj): Remove a specified element from a set.
sample_set.remove('Data') # Delete element Data.
print(sample_set) # {'Prince', 'Techs'}
list2 = [1,3,1,5,3]
print(list(set(list2))) # The output is [1,3,5]. The uniqueness of the set elements is used to
deduplicate the list.
sample_set = frozenset(sample_set)# Invariable set.
Python Lab Guide-Teacher Version Page 5

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
Dict1 = {'name':'lee', 'age':89, 'num':[1,2,8]} # Create a dictionary.
Dict_copy = Dict1.copy() # Shallow copy.
Dict_dcopy = copy.deepcopy(Dict1) # Deep copy.
Dict1['num'][1] = 6 # Change the value of the nested list in the original data.
print('Dict1:'+str(Dict1)+"\n",' Dict_copy:'+ str(Dict_copy)+"\n",' Dict_dcopy:'+ str(Dict_dcopy))

Output:

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


Dict_copy :{'name':'lee', 'age':89, 'num':[1,6,8]} # The shallow copy data is modified.
Dict_dcopy :{'name':'lee', 'age':89, 'num':[1,2,8]} # 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.
score = input("Please enter your score.") # The input function receives input, which is a string.
score = float(score) # 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.
try:
if 100>=score>=90: # Check whether the entered value is greater than the
score of a level.
print("Excellent") # Generate the level when conditions are met.
elif 90 > score >= 80:
print("Good")
elif 80>score>0:
print("Medium")
else:
print("Bad")
except Exception:
print("Enter a correct score.")
Python Lab Guide-Teacher Version Page 6

2.1.3 Loop Statement


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

for i in range(1,10): # Define the outer loop.


for j in range(1,i+1):# Define the inner loop.
# Format the output string to align the generated result. The end attribute is set to /n by default.
print("%d*%d=%2d"%(i,j,i*j), end=" ")
print()

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
i=0 # Create the variable i.
while i<9: # Set a condition for the loop.
i+=1 # The value of i increases by 1 in each loop.
if i == 3: # Check whether the conditions are met.
print("Exit this loop.")
continue # Execute continue to exit the current loop.
if i == 5:
print("Exit the current big loop.")
break # Exit the current big loop.
print(i)

Output

1
2
Exit the current loop.
4
Exit the current big loop.
Python Lab Guide-Teacher Version Page 7

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).

def fibs(num): # Position parameter.


result = [0,1] # Create a list to store the sequence value.
for i in range(2,num): # Cycle num-2 times.
a = result[i-1] + result[i-2]
result.append(a) # Append the value to the list.
return result # Return the list.
fibs(5)

Output:

[0, 1, 1, 2, 3]

Step 2 Generate parameters.


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

def hello(greeting='hello',name='world'): # Default parameters.


print('%s, %s!' % (greeting, name)) # Format the output.
hello() # hello,world Default parameter.
hello('Greetings') # Greetings,world Position parameter.
hello ('Greetings', 'universe') # Greetings, universe Position parameter.
hello (name= 'Gumby') # hello, Gumby Keyword parameter.

Output:

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

3.1.2 Object Orientation


Step 1 Create and use classes.
Python Lab Guide-Teacher Version Page 8

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"""
def __init__ (self,name,age):
"""Initialize the name and age attributes."""
self.name = name
self.age = age
def sit(self):
"""Simulate a dog sitting when ordered."""
print(self.name.title()+"is now sitting")
def roll_over(self):
"""Simulate a dog rolling over when ordered."""
print(self.name.title()+"rolled over!")
Instantiate a class.
dog = Dog ("Husky",2)
dog.sit()
dog.roll_over()
Output:
Husky is now sitting
Husky rolled over!

Step 2 Access attributes.

class Employee:
'Base class of all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d" % Employee.empCount )
def displayEmployee(self):
print("Name : ", self.name, ", Salary: ", self.salary)
# Create the first object of the Employee class.
emp1 = Employee("Zara", 2000)
# Create the second object of the Employee class.
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print("Total Employee %d" % Employee.empCount)

Output:

Name : Zara ,Salary: 2000


Name : Manni ,Salary: 5000
Total Employee 2

Step 3 Inherit a class.


Python Lab Guide-Teacher Version Page 9

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.


parentAttr = 100
def __init__(self):
print("Invoke the parent class to construct a function.")
def parentMethod(self):
print('Invoke a parent class method.')
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print("Parent attribute:", Parent.parentAttr)
class Child(Parent): # Define a child class.
def __init__(self):
print("Invoke a child class to construct a method.")
def childMethod(self):
print('Invoke a child method.')
c = Child() # Instantiate a child class.
c.childMethod() # Invoke the method of a child class.
c.parentMethod() # Invoke the method of a parent class.
c.setAttr(200) # Invoke the method of the parent class again to set the attribute value.
c.getAttr() # 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:
__secretCount = 0 # Private variable.
publicCount = 0 # Public variable.
def count(self):
self.__secretCount += 1
self.publicCount += 1
print(self.__secretCount)
counter = JustCounter()
counter.count()
counter.count()
print(counter.publicCount)
print(counter.__secretCount) # An error is reported, indicating that the instance cannot access private variables.

Output:

1
2
2
Python Lab Guide-Teacher Version Page 10

Figure 3-1 Error Message


Python Lab Guide-Teacher Version Page 11

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
for i in range(100):
print(i)
if i ==5:
sys.exit(0)

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.

sys.path

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.

sys.platform
Python Lab Guide-Teacher Version Page 12

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:

print(sys.argv[1])

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

python test.py hello

Output:

Figure 4-1 Receiving parameters from outside


Step 2 os

import os
# os.getpid() Obtain the current process ID.
print("ID of the current process:", os.getpid())

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


print(" ID of the current parent process:", os.getppid())

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


cwd = os.getcwd()
print(" The current path is:",cwd)

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


os.chdir("C:\\")
print("The modified path is:", os.getcwd())

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


print("Files in the current directory:", os.listdir(cwd))

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


for root, dirs, files in os.walk(cwd, topdown=False):
for name in files:
print(os.path.join(root, name))
for name in dirs:
print(os.path.join(root, name))

Output:
Python Lab Guide-Teacher Version Page 13

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.
print("The absolute path of text.txt is:",os.path.abspath("text.txt")) # The text.txt file is a file in the current folder.
(In the previous experiment, the current path is changed to C:\, and you need to switch back to the original path.)

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

# os.path.getsize(path): Return the file size. If the file does not exist, an error is returned.
print("Size of the text.txt file: ",os.path.getsize("text.txt"))

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


print("Whether text.txt is a file:",os.path.isfile("text.txt"))

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


print("Whether text.txt is a folder:",os.path.isdir("text.txt"))

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_now = time.time()
print("Timestamp:",time_now)

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


localtime = time.localtime(time_now)
print("The local time is:", localtime)

# time.asctime(): Obtain formatted time.


localtime = time.asctime(localtime)
print("The local time is:", localtime)
Python Lab Guide-Teacher Version Page 14

#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.
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

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-Teacher Version Page 15

5 Database Programming

5.1 Database Programming


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

Figure 5-1 Downloading the MySQL


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.
default-character-set=utf8
[mysqld]
# Set the port 3306.
port = 3306
# Set the MySQL installation directory. Replace ## with the installation directory.
basedir=##
# Set the directory for storing the MySQL database data.
Python Lab Guide-Teacher Version Page 16

# datadir=##
# Maximum number of connections allowed.
max_connections=20
# The default character set used by the server is the 8-bit latin1 character set.
character-set-server=utf8
# Default storage engine used when a new table is created.
default-storage-engine=INNODB

Step 2 Start MySQL.


Open the CLI as the administrator, switch to the decompressed folder, and go to the bin directory.

mysqld --initialize –console

After initialization, you obtain a random password in the following format: root@localhost:Random
password.
Run the following command to install the MySQL:

mysqld install

Start the MySQL database.

net start mysql

Log in to the MySQL database.

mysql –uroot –p

Change the password.

set password for User name@localhost = password('New password')

Step 3 Configure environment variables.


Right-click My Computer, choose Properties from the shortcut menu, and select Advanced system
settings.
Python Lab Guide-Teacher Version Page 17

Figure 5-2 System Properties


Click Environment Variables. Add the database path to the path variable.
Python Lab Guide-Teacher Version Page 18

Figure 5-3 Configure environment variables.

5.2 Creating a database


Create database my_database.

create database my_database;

Figure 5-4 Creating a database


Switch the database.
Python Lab Guide-Teacher Version Page 19

use my_database;

Figure 5-5 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.

pip install pymysql

Step 2 Connect to the database.

import pymysql
# Connect to the database.
db = pymysql.connect("localhost", "root", "mysql", "my_database", charset='utf8' )
# 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.
cursor = db.cursor()
# Execute the SQL statement using the execute method.
cursor.execute("SELECT VERSION()")
# Use the fetchone() method to obtain a data record.
data = cursor.fetchone()
print("Database version : %s " % data)

Output:

Database version : 8.0.15

Step 3 Use Python to operate the database.

import pymysql
# Connect to the database.
db = pymysql.connect("localhost", "root", "mysql", "my_database", charset='utf8' )
# Use the cursor() method to obtain the operation cursor.
cursor = db.cursor()
# SQL statement for creating a data table.
sql = """CREATE TABLE my_table (
id int,
name varchar(50))"""
# Run the following commands:
cursor.execute(sql)
# Close the database connection.
db.close()

Check the result in the MySQL database.


Python Lab Guide-Teacher Version Page 20

show tables;

Figure 5-6 Checking the MySQL database


Step 4 Data operations
Insert data.

import pymysql

# Connect to the database.


db = pymysql.connect("localhost", "root", "mysql", "my_database", charset='utf8' )
# Use the cursor() method to obtain the operation cursor.
cursor = db.cursor()

# Execute the SQL INSERT statement.


sql = """INSERT INTO my_table(id,
name)
Values (1,'Zhang San')"""# You only need to modify the SQL statement to be executed to delete or
modify the data.
try:
# Execute the SQL statement.
cursor.execute(sql)
# Submit data to the database for execution.
db.commit()
except:
# Rollback upon an error.
db.rollback()

# Close the database connection.


db.close()

View the result in the database.

select * from my_table;

Figure 5-7 Viewing the inserted data


Python Lab Guide-Teacher Version Page 21

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 created.
Str = input("Please enter the content to be written:")
f.write(Str)
f.close()

Output

Figure 6-1 Content to be written

Figure 6-2 File content

Step 2 Read file data.

f = open("text.txt", 'r')
print(f.read(6)) # Read six characters and move the cursor six characters backward.
print(f.read()) # Read from the current position of the cursor to the end.
f.close()

Output

python
Operation

Step 3 Use the context manager to operate the file.


Python Lab Guide-Teacher Version Page 22

# Use the with statement to write file data.


with open("text1.txt", 'w') as f:
f.write("Python file operation")
# Use the with statement to read the file content.
with open("text1.txt", 'r') as f:
print(f.read())

Output

Python file operation

Step 4 Use the OS module to operate the file.

import os
os.rename("text.txt","text0.txt") # Rename the file.
os.remove("text1.txt") # Delete the file.
Python Lab Guide-Teacher Version Page 23

7 Multitask Experiment

7.1 Multiple Tasks


7.1.1 Multitask Programming
Step 1 Multiple threads
Use multiple threads to execute tasks.

import threading
from time import sleep,ctime
def work1():
for i in range(3):
print("work1 is being executed...%d"%i)
sleep(1)

def work2():
for i in range(3):
print("work2 is being executed...%d"%i)
sleep(1)

if __name__ == '__main__':
print('---Start---:%s'%ctime())

t1 = threading.Thread(target=work1) # Thread 1
t2 = threading.Thread(target=work2) # Thread 2
# Start the thread.
t1.start()
t2.start()

sleep(5)
print('---End---:%s' %ctime())

Output:

---Start---:Mon Apr 15 10:55:16 2019


work1 is being executed...0
work2 is being executed...0
work1 is being executed...1
work2 is being executed...1
work1 is being executed...2
work2 is being executed...2
---End---:Mon Apr 15 10:55:21 2019

Thread synchronization
Python Lab Guide-Teacher Version Page 24

import threading
import time
g_num = 0
def test1(num):
global g_num # Use global variables.
for i in range(num):
Mutex.acquire() # Lock
g_num += 1
Mutex.release() # Unlock
print("---test1---g_num=%d"%g_num)

def test2(num):
global g_num
for i in range(num):
Mutex.acquire() # Lock
g_num += 1
Mutex.release() # Unlock

print("---test2---g_num=%d"%g_num)

# Create a mutual exclusion lock.


# By default, the global variables are not locked. You can delete the lock and view the resource contention result.
mutex = threading.Lock()

# Create two threads and add 1000000 times for g_num.


p1 = threading.Thread(target=test1, args=(1000000,))
p1.start()

p2 = threading.Thread(target=test2, args=(1000000,))
p2.start()

# Wait for the calculation to be complete.


time.sleep(5)

print("The final result after operations are performed on the same global variable by two threads:%s" % g_num)

Output:

---test2---g_num=1971982---test1---g_num=2000000

After two threads operate the same global variable, the final result is as follows: 2000000

Step 2 Multiple processes

from multiprocessing import Process


import os
import time

nums = [11, 22]

def work1():
"""Code to be executed by the subprocess"""
print("in process1 pid=%d ,nums=%s" % (os.getpid(), nums)) # Obtain the process ID.
for i in range(3):
nums.append(i)
Python Lab Guide-Teacher Version Page 25

time.sleep(1)
print("in process1 pid=%d ,nums=%s" % (os.getpid(), nums))

def work2():
"""Code to be executed by the subprocess"""
print("in process2 pid=%d ,nums=%s" % (os.getpid(), nums))

if __name__ == '__main__':
p1 = Process(target=work1)
p1.start()
p1.join()

p2 = Process(target=work2)
p2.start()

Output:

in process1 pid=9932 ,nums=[11, 22]


in process1 pid=9932 ,nums=[11, 22, 0]
in process1 pid=9932 ,nums=[11, 22, 0, 1]
in process1 pid=9932 ,nums=[11, 22, 0, 1, 2]
in process2 pid=13524 ,nums=[11, 22]
# Note: The Jupyter Notebook does not generate the result of this experiment because of the editor. You can
create a .py file, write the code to the file, and run the file on the CLI.
Python Lab Guide-Teacher Version Page 26

8 Regular Expression Experiment

8.1 Introduction
8.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:

re.match(pattern, string, flags=0)

Example:

import re
print(re.match('www', 'www.huawei.com').span()) # Match at the start position.
print(re.match('com', 'www.huawei.com')) # 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:

re.search(pattern, string, flags=0)

Example:

import re
line = "Cats are smarter than dogs"
searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)
if searchObj:
print("searchObj.group() : ", searchObj.group())
print("searchObj.group(1) : ", searchObj.group(1))
print("searchObj.group(2) : ", searchObj.group(2))
else:
print("Nothing found!!" )

Output:
Python Lab Guide-Teacher Version Page 27

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:

re.sub(pattern, repl, string, count=0, flags=0)

Example:

import re
phone = "2019-0101-000 # This is a phone number."
# Delete the Python comment in the string.
num = re.sub(r'#.*$', "", phone)
print("The phone number is: ", num)
# Delete the hyphens from the phone number.
num = re.sub(r'\D', "", phone)
print("The phone number is: ", num)

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:

re.compile(pattern[, flags])

Example:

import re
pattern = re.compile(r'\d+') # At least one digit is matched.
n = pattern.match('one12twothree34four') # The header is not found.
print(n)

m = pattern.search('one12twothree34four') # Match from the position of 'e'. No match is found.


print(m)
print(m.group())

Output:

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

Step 5 re.split()
Python Lab Guide-Teacher Version Page 28

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

re.split(pattern, string[, maxsplit=0, flags=0])

Example:

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

Output:

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


Python Lab Guide-Teacher Version Page 29

9 Generators, Iterators, and Decorators

9.1 Procedure
9.1.1 Iterator
Step 1 Determine an iterable object.

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


from collections import Iterable # Iterable object.
print(isinstance([], Iterable))
print(isinstance('abc', Iterable))
print(isinstance(100, Iterable))

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]
l_iter = iter(l)
next(l_iter)
1
next(l_iter)
2

Step 3 Determine an iterator.

from collections import Iterator # Iterator.


print(isinstance([], Iterator))
print(isinstance(iter([]), Iterator))

Output:

False
True
Python Lab Guide-Teacher Version Page 30

9.1.2 Generators
Step 1 Create a generator through list derivation.

G = ( x*2 for x in range(5))


print(type(G))

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.

def fib(n):
current = 0
num1, num2 = 0, 1
while current < n:
num = num1
num1, num2 = num2, num1+num2
current += 1
yield num
return 'done'
g=fib(5)
while True:
try:
x = next(g)
print("value:%d"%x)
except StopIteration as e:
print("Generator return value:%s"%e.value)
break

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.

def gen():
i=0
while i<5:
temp = yield i
print(temp)
Python Lab Guide-Teacher Version Page 31

i+=1
f = gen()
next(f)
>>>0
f.send('haha')
>>>haha
>>>1
next(f)
>>>None
>>>2

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

import time
def func(f):
def inner(*args, **kwargs):
start_time = time.time()
f(*args, **kwargs)
end_time = time.time()
print('Consumed time:%s second' % (end_time - start_time))
return inner

Step 2 Use the decoration function.

@func
def test():
time.sleep(2)

test()

Output:

Time consumed: 2.000276803970337 seconds


Python Lab Guide-Teacher Version Page 32

10 Treasury Management System

10.1 Introduction
10.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.

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

10.2 Procedure
10.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.

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

create database money;

Create a data table.

CREATE TABLE user(


username varchar(30) PRIMARY KEY,
pwd VARCHAR(100) NOT NULL,
start_time DATETIME NOT NULL,
end_time DATETIME NOT NULL,
balance FLOAT NOT NULL
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
Python Lab Guide-Teacher Version Page 33

Insert data.

INSERT INTO user (username, pwd, start_time, end_time, balance)


VALUES ('admin','123456','2019.04.23', '2019.04.23',100.0);
INSERT INTO user (username, pwd, start_time, end_time, balance)
VALUES ('root','admin','2019.01.01', '2019.02.02',100.0);

Step 2 Import the required library and define the operation dictionary.

import time
import sys
import pymysql
import getpass
action_dict = {1:"deposit", 2: "withdrawal", 3:"transfer", 4:"change password", 5:'Exit'}

Step 3 Database connection


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):
try:
db = pymysql.connect("localhost", "root", "mysql", "money", charset='utf8' )
# Use the cursor() method to obtain the operation cursor.
cursor = db.cursor()
# Execute the SQL statement using the execute method.
cursor.execute(sql)
results = cursor.fetchone()# Query a data record.
db.commit() # Submit the data to the database.
except Exception as e:
db.rollback()
print("System error")
sys.exit()
db.close() # Close the database.
return results

Test method:

sql = "select * from user"


con_mysql(sql)

Output:
Python Lab Guide-Teacher Version Page 34

Figure 10-1 Database connection test result


Step 4 Define a user class.

class Account(object):
def __init__(self, username,money,number=0):
self.money = money # Account balance.
self.username = username # User name.
# Last login time.
self.start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.number = number
# Deposit.
def save(self):
self.money += self.number
print("Saved CNY %f"%(self.number))
# Withdrawal.
def take(self):
if self.number > self.money:
print("Insufficient balance")
return 0
else:
self.money -= self.number
print (" Withdraw CNY %f"%(self.number))
return 1
# Change the password.
def update(self):
pwd = getpass.getpass("Enter a new password:")
sql = "update user set pwd=%s where username=%s"%(pwd, self.username)
return sql
# Transfer.
def transfer(self):
user = input("Please enter the transferee.")
if self.number > self.money:
print("Insufficient balance")
return
else:
sql = "select username from user where username='%s'"%(user)
result = con_mysql(sql)
if result == None:
print ("The transferee does not exist.")
self.number=0
else:
return user
# Perform the selected operation.
Python Lab Guide-Teacher Version Page 35

def implement(self, action):


if action == 5:
sys.exit()
elif action == 1:
try:
self.number = float (input("Please enter the deposit amount:"))
except Exception as e:
print("Enter a correct amount.")

self.save()
elif action == 2:
try:
self.number = float (input("Please enter the amount to be withdrawn:"))
except Exception as e:
print("Enter a correct amount.")
if self.take():
sql = "update user set balance=%f where username=%s"%(self.number,self.username)
con_mysql(sql)
elif action == 3:
try:
self.number = float (input("Please enter the transfer amount."))
except Exception as e:
print("Enter a correct amount.")
User = self.transfer()
if User:
sql = "update user set balance=%f where username=%s"%(self.number,User)
con_mysql(sql)
else:
self.update()
# Generate the credential after the operation.
def voucher(self,end_time, action):
str_action = """user:%s \n operation:%s\n Operation amount: %s\n Login time:
%s\n End time: %s"""%(self.username, action_dict[action], self.number, self.start_time,
end_time)
with open("%s.txt"%(self.username), 'w') as f:
try:
f.write(str_action)
except Exception as e:
print("The credential fails to be generated. Please contact the administrator.)
print ("Generation succeeded. Keep it safely.")

Step 5 Login function

def login():
"""
Check user login.
:param username: Account
:param pwd: User Password
:return:
"""
username = input ("Please enter your account:")
pwd = getpass.getpass("Please enter your password:") # Hide the entered password.
# compile an SQL statement to obtain account information from the database.
sql = "select * from user where username='%s'"%(username)
result = con_mysql(sql)
Python Lab Guide-Teacher Version Page 36

if result:
if result[1] == pwd:
user_account = Account(result[0], result[4])
return user_account
else:
print("Incorrect account or password.")
else:
print("The account does not exist.")

Test the login function:

user_account = login()
user_account

Output:

Figure 10-2 Login function test


Step 6 Welcome window

def welcome():
print(' *'*15)
print(" %s%30s"%("*","*"))
print(" %s Welcome to the Treasury Management System %5s"%("*","*"))
print(" %s%30s"%("*","*"))
print(' *'*15)
try:
action = input("Please select the operation: 1. Deposit 2. Withdraw 3. Transfer 4. Change Password 5.
Exit:")
action = int(action)
except Exception as e:
print("warn: Please enter a correct operation command.")
return -1
if action not in action_dict:
print("warn: Please perform a correct operation.")
return -1
return action

Test the welcome method:

action = welcome()
action

Output:
Python Lab Guide-Teacher Version Page 37

Figure 10-3 Welcome window


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

def run():
action = welcome()
user_account.implement(action)
end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
sql = """
update user set balance=%f,start_time='%s',end_time='%s' where username='%s'
"""%(user_account.money, user_account.start_time,end_time,user_account.username)
con_mysql(sql)
user_account.voucher(end_time, action)

Step 8 Add the timing function to the system using the decorator.
Define the decorator.

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


def inner(*args, **kwargs):

start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())


print ("Current login time %s"%(start_time))
func()
end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print ("Logout time %s"%(end_time))
return (start_time, end_time)
return inner

Add the following function to the system startup function:

@consume_time
def run():
action = welcome()
user_account.implement(action)
end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
sql = """
Python Lab Guide-Teacher Version Page 38

update user set balance=%f,start_time='%s',end_time='%s' where username='%s'


"""%(user_account.money, user_account.start_time,end_time,user_account.username)
con_mysql(sql)
user_account.voucher(end_time, action)

Step 9 Starting the System

if __name__ == "__main__":
user_account = login()
while True:
if isinstance(user_account, Account):
break
while True:
run()

Output:

Figure 10-4 System execution result

Figure 10-5 Generated credential

You might also like