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".
# Generate "hello world". The output is the same when single and double quotation marks are
carried in input.
# The output is 6.6. By default, the sum of numbers of different precisions is the number of the
highest precision type.
# 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.
# 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.
# 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.
# 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: [12,32,45,55]
# Output: [55,45,32,12]
# Create a tuple.
# Create a tuple.
# (12,45,32,55,[2,0,3])
# {'food':'Spam','quantity':4,'color':'pink'}
# {'food':'Spam','quantity':4,'color':'red'}
# Element access.
# Obtain the error information.
# Output: None
# Output: {}
# The program is abnormal, and a message is displayed, indicating that d is not defined.
# 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: 3
# {'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.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.
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.
# Check whether the entered value is greater than the score of a level.
# 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
# while loop
# Create the variable i.
Output
1
2
Exit the current loop.
4
Exit the current big loop.
Python Lab Guide-Student Version Page 9
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.
Output:
[0, 1, 1, 2, 3]
# Default parameters.
Output:
hello, world!
Greetings, world!
Greetings, universe!
hello, Gumby!
class Dog():
"""A simple attempt to simulate a dog"""
Output:
class Employee:
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.
# 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:
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.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.
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']
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:
import os
# os.getpid() Obtain the current process ID.
Output:
Python Lab Guide-Student Version Page 14
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.
Output:
Step 3 time
import time
# time.time(): Obtain the current timestamp.
#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
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
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
[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.
# The default character set used by the server is the 8-bit latin1 character set.
Step 2
Step 3 Start MySQL.
Open the CLI as the administrator, switch to the decompressed folder, and go to the bin
directory.
Right-click My Computer, choose Properties from the shortcut menu, and select
Advanced system settings.
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.
Output:
import pymysql
# Connect to the database.
import pymysql
# You only need to modify the SQL statement to be executed to delete or modify the data.
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
f = open("text.txt", 'r')
# Read six characters and move the cursor six characters backward.
Output
python
Operation
Python Lab Guide-Student Version Page 26
Output
import os
# Rename the file.
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.
Output:
(0, 3)
None
Example:
import re
Python Lab Guide-Student Version Page 28
Output:
Example:
import re
phone = "2019-0101-000 # This is a phone number."
# Delete the Python comment in the string.
Output:
Example:
import re
# At least one digit is matched.
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:
8.1 Procedure
8.1.1 Iterator
Step 1 Determine an iterable object.
Output:
True
True
False
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'>
Output:
value:0
value:1
value:1
value:2
value:3
Generator return value: done
>>>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
@func
def test():
Output:
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.
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:
Output:
class Account(object):
Python Lab Guide-Student Version Page 35
# Account balance.
# User name.
# Deposit.
def save(self):
# Withdrawal.
def take(self):
# Transfer.
def transfer(self):
Login function
user_account = login()
user_account
Output:
Python Lab Guide-Student Version Page 36
def welcome():
action = welcome()
action
Output:
def run():
@consume_time
def run():
Python Lab Guide-Student Version Page 37
Output: