02 Python Lab Guide-Student Version
02 Python Lab Guide-Student Version
Python
Lab Guide
Teacher Version
1
Contents
1.1 Procedure
1.1.1 Hello world
The first Python program generates "hello world".
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.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:
2.1.2 if Statement
You can use the if statement in Python to determine the level of a score input by a user.
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
# 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.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).
Output:
[0, 1, 1, 2, 3]
Output:
hello, world!
Greetings, world!
Greetings, universe!
hello, Gumby!
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!
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:
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.
Output:
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
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
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
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.
Output:
import os
# os.getpid() Obtain the current process ID.
print("ID of the current process:", os.getpid())
Output:
Python Lab Guide-Teacher Version Page 13
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"))
Output:
Step 3 time
import time
# time.time(): Obtain the current timestamp.
time_now = time.time()
print("Timestamp:",time_now)
#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
[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
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
mysql –uroot –p
use my_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:
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()
show tables;
import pymysql
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
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
Output
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
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:
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)
p2 = threading.Thread(target=test2, args=(1000000,))
p2.start()
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
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:
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:
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
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
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:
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)
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:
Example:
import re
s = re.split('\W+', 'www.huawei.com')
print(s)
Output:
9.1 Procedure
9.1.1 Iterator
Step 1 Determine an iterable object.
Output:
True
True
False
l = [1, 2, 3, 4, 5]
l_iter = iter(l)
next(l_iter)
1
next(l_iter)
2
Output:
False
True
Python Lab Guide-Teacher Version Page 30
9.1.2 Generators
Step 1 Create a generator through list derivation.
Output:
<class 'generator'>
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
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
@func
def test():
time.sleep(2)
test()
Output:
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.
Insert data.
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'}
# 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:
Output:
Python Lab Guide-Teacher Version Page 34
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
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.")
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.")
user_account = login()
user_account
Output:
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
action = welcome()
action
Output:
Python Lab Guide-Teacher Version Page 37
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.
@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
if __name__ == "__main__":
user_account = login()
while True:
if isinstance(user_account, Account):
break
while True:
run()
Output: