Chapter 2 - Data Processing Tools (Python Basics)
Chapter 2 - Data Processing Tools (Python Basics)
计算机应用技术系
Chapter Two Data Processing Tools
1 Tool Introduction
Contents
2 Python language development environment 目录
3.3 3.3
Input and Output
中国石油大学(华东) 计算机应用技术系
Data Types
中国石油大学(华东) 计算机应用技术系
Arithmetic operators
+ Addition or positive sign operations The result of 10+20 is 30, and the result of +1 is 1
- Subtraction or negative sign operation The results of 10 - 20 are -10, and the result of -1 is-1
// Integer division operation The result of 5/2 is 2.5. The result of 2.0/2 is 2.0
中国石油大学(华东) 计算机应用技术系
Compound assignment operator
>>>a += b #Equivalent to a = a + b
>>>a -= b #Equivalent to a = a-b
>>>a *= b #Equivalent to a = a * b
>>>a /= b #Equivalent to a = a / b
>>>a %= b #Equivalent to a = a% b
>>>a **= b #Equivalent to a = a ** b
>>>a //= b #Equivalent to a = a // b
中国石油大学(华东) 计算机应用技术系
Relation operator
中国石油大学(华东) 计算机应用技术系
Logical operator
and x and y If x is False, do not calculate y; the result is x. Otherwise, the result is y.
not not x If x is True, the result is False; if x is False, the result is True.
中国石油大学(华东) 计算机应用技术系
Member operator
Used to determine whether an element is in a sequence, such as a string, list, or tuple.
中国石油大学(华东) 计算机应用技术系
Formatted output
1) Format using the% symbol
>>> x,y=3,4
中国石油大学(华东) 计算机应用技术系
Basic Input
When using the input() function to read data, Python stores it as a string in a
variable. Using this variable as a numeric value will result in an error.
To address the aforementioned issues, you can use the int() function to
convert strings to integer data, or the float() function to convert strings to
floating-point data.
To input multiple data values simultaneously, use the eval() function. The
eval() function requires data separated by commas.
中国石油大学(华东) 计算机应用技术系
Common built-in mathematical functions
Built-in functions are functions that can be used directly without importing any modules. A function is a piece of
code in a program that is packaged to perform specific tasks. Functions are called using their names and
parameter lists, and return results externally through their return values.
function explain
abs(x) Returns the absolute value of x
max(x1,x2,…, xn ) Returns the maximum value of x1, x2,..., xn, with no limit on n.
min(x1,x2,…, xn ) Returns the minimum value of x1, x2,..., xn, with no limit on n.
中国石油大学(华东) 计算机应用技术系
Built-in data type conversion function
function explain
int (x) Convert x to a decimal integer. x can be a floating-point number or a string.
Generate a complex number with real and imag parts. The real part can be
complex(real[, imag]) an integer, floating-point number, or string, and the imag part can be an
integer or floating-point number but not a string.
str (x) Convert x to a string. x can be an integer or floating-point number.
中国石油大学(华东) 计算机应用技术系
Common Standard Function Library
How to import the standard function library
(1)Import the entire function library
The basic format for importing the entire function library is as follows:
Import library name [as alias]
After importing a function library this way, you must prefix the function name with the library name
when calling functions in the library. The reference format is as follows:
library name .function name
>>>import math #Import the standard library math
>>> [Link](3,2) #Calls the pow() function in the math library to calculate the square root of 3
9.0
>>> import random as r #Import the standard library random and assign it the alias r
>>> [Link](1,100) #Generates a random integer between [1,100]
12
中国石油大学(华东) 计算机应用技术系
Common Standard Function Library
(2) Import specific functions
When you only need to call a specific function in the library, you can import only that
function. The basic format is as follows:
from alias import function name [as alias]
>>> from math import sqrt #Only import the specified function sqrt from the math library
>>> sqrt(9) #Calls the sqrt() function to calculate the square root of 9
3.0
>>> from random import randint as r
>>> r(1,10) # Calls a function to generate a random integer in the range
[1,10]
7
中国石油大学(华东) 计算机应用技术系
Common Standard Function Library
(3) Import all functions from the library
Use the asterisk "*" to import all contents from the library, including functions and variables.
The basic format is as follows: from module_name import *
>>> from math import * #Import all content from the standard library math
>>>pi # Constant π
3.141592653589793
>>> log(9,3) # Calls the log() function to calculate the logarithm base 3
2.0
>>> ceil(5.26) # Calls the ceil() function to round up 5.26 to the nearest integer
6
中国石油大学(华东) 计算机应用技术系
Math storeroom
Mathematical
function explain instance
notation
Returns the absolute value of x as a floating-
[Link] (x) x
point number.
[Link](-3) returns 3.0
[Link] (x) 𝑥 Returns the square root of x [Link] (16) returns 4.0
[Link] (x) sin 𝑥 Returns the sine function value of x in radians. [Link]([Link]/2) returns 1.0
中国石油大学(华东) 计算机应用技术系
Chapter 2 Data Processing Tools
• Index operation
>>> s='Python’
>>> s[0]
‘P’
>>> s[-3]
‘h’
>>> s[6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
中国石油大学(华东) 计算机应用技术系
String operations
• sectioning
The complete format is: variable[start: end: [step]], indicating a substring extracted from
start to end-1 with every step characters. Both indices can be omitted.
中国石油大学(华东) 计算机应用技术系
String operations
• sectioning
>>> s =‘ILovePython’
>>> s[0:5] #Extract substring with index 0-4 from string s
'ILove' #Output result substring
>>> s[-6:] #The slice range omits the subscript, defaulting to the last character
‘Python’ #Returns substring results with indices ranging from-6 to-1
>>> s[:5] #The slice range omits the subscript, defaulting to slicing from the first character
'ILove’ #The output index is a result substring in the range of 0~4
>>> s[1:9:2] #Extracts from index 1 to index 8, extracting one character every 2 characters
'LvPt'
中国石油大学(华东) 计算机应用技术系
String operations
• search operation
The index() method is formatted as: [Link](sub[start[, end]])
中国石油大学(华东) 计算机应用技术系
String operations
• search operation
The find() method is formatted as: [Link](sub[,start[, end])
Difference from the index() method: When a match is not found, the find() method returns-1,
whereas the index() method throws an exception.
中国石油大学(华东) 计算机应用技术系
String operations
• Length measurement operation
The format of the len() method is: len(seq), which means to view the length of the specified
[Link] method can also be applied to other data types such as lists, tuples, and dictionaries.
中国石油大学(华东) 计算机应用技术系
String operations
中国石油大学(华东) 计算机应用技术系
String operations
• Connection operation — join method for string concatenation
The join method format is: ‘sep’. join seq
Here, sep denotes the delimiter, which can be empty; seq represents
the element sequence to be connected.
>>> ls = [‘2023’, ’03’, ’08’] # Create a list ls with all elements as strings
>>> ‘-’.join(ls)
‘2023-03-08’ # Combine three strings from ls into one string using the delimiter ‘-’
中国石油大学(华东) 计算机应用技术系
String operations
>>> s = "Hi..."
>>> s *= 3 # Copy "Hi..." three times to create a new string object
>>> s #View s content
‘Hi...Hi...Hi...’ #String data after 3 copies
中国石油大学(华东) 计算机应用技术系
String operations
• Split operation
The split() method takes the following format: [Link](sep, num)[n]
The sep parameter specifies the delimiter to be used. It can be omitted, with space being
the default. When omitted, the entire string is returned as a list element.
num indicates the number of divisions, splitting the string into num+1 substrings.
[n]: Selects the element at index n in the returned list, starting from 0.
中国石油大学(华东) 计算机应用技术系
String operations
• Split operation
>>> str = ‘[Link]’
>>> [Link](‘.’) #Specifies ‘.’ as the delimiter to split the string str
[www, upc, edu, cn] #with delimiter . Divide the entire string into multiple substrings to form a list
>>> [Link] (‘.’, 2) #Specifies the delimiter as ‘.’ and the split count as 2 times
[‘www’, ‘upc’, ‘[Link]’] #Using the delimiter ‘.’ splits the entire string into 2+1 substrings to
form a list
>>> [Link](‘.’) [1] #Specifies the delimiter as ‘.’ and extracts the element at index 1 in the sequence
中国石油大学(华东) 计算机应用技术系
String operations
• Statistical operations
among ,
The start parameter specifies the position where the string search begins. It can be
omitted, with the default being the first character.
The end parameter specifies the search termination position in the string and can be
omitted, defaulting to the last position.
中国石油大学(华东) 计算机应用技术系
String operations
• Statistical operations
中国石油大学(华东) 计算机应用技术系
Chapter 2 Data Processing Tools
中国石油大学(华东) 计算机应用技术系
List operations
• Create list
You can convert strings or tuples into lists using the list() function.
>>> list("Give China a thumbs up!") #list() function converts string data into a list
['G', 'i', 'v', 'e', ' ', 'C', 'h', 'i', 'n', 'a', ' ', 'a', ' ', 't', 'h', 'u', 'm', 'b', 's', ' ', 'u', 'p', '!']
>>> list((1, ‘a’, 3.14)) # The list() function converts tuple data into a list
[1, ‘a’, 3.14]
中国石油大学(华东) 计算机应用技术系
List operations
• Indexing and Slicing Operations
中国石油大学(华东) 计算机应用技术系
List operations
中国石油大学(华东) 计算机应用技术系
List operations
• Add operation — Slice method
>>> ls1[len(ls1):] = [135] #Add a new element at the end of the list
>>> ls1
[104, 107, 109, 113, 118, 135]
>>> ls1[:0] = [128,126] #Add a new element to the list header
>>> ls1
[ 128, 126, 104, 107, 109, 113, 118, 135]
>>> ls1[3:3] = [100] #Add a new element at index 3
>>> ls1
[128, 126, 104, 100, 107, 109, 113, 118, 135]
中国石油大学(华东) 计算机应用技术系
List operations
• Add operation — append() method
The append() method adds a new element to the end of a list.
Its format is: [Link] (obj)
中国石油大学(华东) 计算机应用技术系
List operations
• Add operation — extend() method
The extend() method adds a specified list of elements to the end of an existing list.
Its format is: [Link] (seq)
Here, the parameter seq represents the list of elements to be added, which can be any
iteratable data type (primarily strings, lists, tuples, or dictionary types).
中国石油大学(华东) 计算机应用技术系
List operations
• Add operation — extend() method
>>> ls3 = [1,2,3,4]
>>> [Link]([5, ‘abc’])
>>> ls3
[1, 2, 3, 4, 5, ‘abc’ ]
>>> [Link](‘python’)
>>> ls3
[1, 2, 3, 4, 5, ‘abc’ , ‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]
Note: The extend() method splits elements from a list and adds them
back to the original list, effectively expanding it. The result is similar to
concatenating strings.
中国石油大学(华东) 计算机应用技术系
List operations
• Add operation — insert() method
The insert() method inserts a specified new element into a list at a given position.
Its format is: [Link] (index, obj)
Here, index denotes the index value where the new element is to be inserted.
The obj parameter specifies the new element to insert into the list, which can be any data type.
中国石油大学(华东) 计算机应用技术系
List operations
• Delete operations — del, pop()
中国石油大学(华东) 计算机应用技术系
List operations
• Delete operations — clear(), remove()
>>> colors = [ ‘red’,’blue’,’green’,’purple’,’blue’]
>>> [Link](‘blue’) #Remove the first matching item with the value ‘blue’
>>> colors
[ ‘red’,’green’,’purple’,’blue’]
>>> [Link] () #Clear all elements from the colors list
>>> colors
[]
The remove() method deletes only the first specified value. To remove multiple
specified values, use a loop.
中国石油大学(华东) 计算机应用技术系
List operations
• Edit operations: Indexing and slicing methods
中国石油大学(华东) 计算机应用技术系
List operations
• Edit operations: Indexing and slicing methods
Adhere to the principle of "more increases and fewer decreases"
>>> mlist
[1, ‘funny’, 3.14, ‘python’, 5]
>>> mlist[1:3] = [ more,’2.56’,’new’]
>>> mlist
[1, ‘more’, 2.56, ‘new’, ‘python’, 5]
>>> mlist[1:3] = [ ‘fewer’]
>>> mlist
[1, ‘fewer’, ‘new’, ‘python’, 5] #The list elements have been reduced, with the
element containing value 2.56 removed
中国石油大学(华东) 计算机应用技术系
Chapter 2 Data Processing Tools
中国石油大学(华东) 计算机应用技术系
Operation on tuples
• Multivariate synchronous assignment of tuples
>>> a, b = (‘good’, ‘better’) # Multi-variable synchronous assignment, parentheses
can be omitted
>>> print(a, b) #outputs variable a and variable b
good better
>>> a, b = b, a # Enables data exchange through tuples, omitting parentheses
>>> print(a, b) # Output the swapped variables a and b
better good
Other common tuple operations (such as indexing, slicing, searching, joining, and
statistics) are similar to those for strings and lists.
中国石油大学(华东) 计算机应用技术系
Chapter 2 Data Processing Tools
• Create dictionary
The dictionary format is: {<key1: value1>, <key2: value2>,..., <keyn: valuen>} where
key-value pairs are unordered and non-duplicate. Keys and values can be any data
type.
>>> student = {1001:’Mike’,1002:’Amely’,1005:’Cindy’}
>>> student #View all key-value pairs in the dictionary
{1001: ‘Mike’, 1002: ‘Amely’, 1005: ‘Cindy’}
中国石油大学(华东) 计算机应用技术系
Dictionary operations
• search operation
Find the value corresponding to the specified key
中国石油大学(华东) 计算机应用技术系
Dictionary operations
• retouching operation
If the key exists, the original key value is updated with the new value. If the key does
not exist, it is added to the dictionary as a new key-value pair.
中国石油大学(华东) 计算机应用技术系
Dictionary operations
• Delete operation — del command
中国石油大学(华东) 计算机应用技术系
Dictionary operations
• Delete operation — pop()
The pop() method has the following format: [Link](key, default)
Its function is: if the key exists, it returns the corresponding value and removes the specified
key-value pair from the dictionary; otherwise, it returns the default value.
>>> Stu = {‘No’: 1001, ‘Name’: ‘Cindy’, ‘age’: 28}
>>> [Link] (‘age’)
28
>>> Stu #View dictionary content, key-value pair {‘age’: 28} was deleted
{‘No’: 1001, ‘Name’: ‘Cindy’}
>>> [Link] (‘tele’, 15160060060) #The key ‘tele’ does not exist. The default value is
returned.
15160060060
中国石油大学(华东) 计算机应用技术系
Dictionary operations
• Permutation operations: keys(), values(), and items() methods
>>> Stu = {‘No’: 1001, ‘Name’: ‘Cindy’, ‘age’: 28, ‘score’: [100, 98]}
>>> Stu_keys () #Returns all key information in the Stu dictionary
dict_keys([‘No’, ‘Name’, ‘age’, ‘score’])
>>> Stu_values () #Returns all value information from the Stu dictionary
dict_values([1001, ‘Cindy’, 28, [100, 98]])
>>> [Link] () #Returns all key-value pairs in the Stu dictionary
dict_items([(‘No’, 1001), (‘Name’, ‘Cindy’), (‘age’, 28), (‘score’, [100, 98])])
中国石油大学(华东) 计算机应用技术系
Dictionary operations
• Permutation operations: keys(), values(), and items() methods
>>> vlist = list( [Link] ())
>>> vlist #View the converted list content
[‘No’, ‘Name’, ‘age’, ‘score’]
>>> list( [Link] ())
[1001, ‘Cindy’, 28, [100, 98]]
中国石油大学(华东) 计算机应用技术系
Chapter 2 Data Processing Tools
5.2 function
Sequential structure
中国石油大学(华东) 计算机应用技术系
Sequential structure
[Example 1] Calculate the area of a triangle.
【 problem description 】
Enter the three sides of a triangle (assuming the given sides satisfy the triangle
condition: the sum of any two sides is greater than the third side), calculate the
area, and output the result.
【 problem analysis 】
The key to solving this problem lies in identifying the formula for calculating the
area of a triangle.
1
Area = s − 𝑠 − 𝑎 𝑠 − 𝑏 𝑠 − 𝑐 , 𝑎𝑚𝑜𝑛𝑔 𝑠 = a + b + c。
2
中国石油大学(华东) 计算机应用技术系
Sequential structure
Import math #Import math library
a, b, c = eval (input(‘Please enter the three sides of the triangle: a, b, c:’))
s=1/2*(a+b+c)
area = [Link](s*(s-a)*(s-b)*(s-c))
print(The area of the triangle is:’, area)
Output result:
Enter the three sides of the triangle a, b, c: 3, 4, 5
The area of the triangle is: 6.0
中国石油大学(华东) 计算机应用技术系
subjective item 5 minutes
problem description :
Enter a 3-digit positive integer n to calculate the sum of its digits.
import :
An integer n.
output :
The sum of the digits of n.
Sample input:
123
Sample output:
6
To use subjective questions, you need version 2.0 or later of Rain Classroom.
respondence
4/12/2026 63
Select structure-single branch
[Example 2] Enter two integers on the keyboard and display them in descending
order.
a, b = eval("Please enter two integers:")
if a < b:
a, b = b, a # Swap the values of two variables
print("larger number:%d; smaller number:%d"% (a, b))
computational results :
Enter two integers: 9,5
Greater number: 9; Smaller number: 5
中国石油大学(华东) 计算机应用技术系
Select structure – dual branches
[Example 3] Enter a college students student ID via keyboard input. Determine and output
whether the student is enrolled in the School of Computer Science based on the student ID
code. The 3rd and 4th digits of the student ID indicate their affiliated college, where 07
signifies enrollment in the School of Computer Science.
Sno = input("Please enter the student ID:")
academy = Sno[2:4]
if academy == ’07’ :
print("This student is enrolled in the School of Computer Science")
else:
print("This student is not enrolled in the School of Computer Science")
computational results :
Enter student ID: 2207020101
The student is enrolled in the School of Computer Science.
中国石油大学(华东) 计算机应用技术系
subjective item 5 minutes
problem description :
Enter an integer and determine whether it is divisible by both 3 and 7. If so,
output "Yes"; otherwise, output "No".
input:
integer n。
output :
Check if n is divisible by both 3 and 7. Return Yes if so, otherwise return No.
To use subjective questions, you need version 2.0 or later of Rain Classroom.
respondence
4/12/2026 66
Select structure – dual branches
Implemented using conditional expressions, with the statement structure format as:
<expression1> if <condition> else <expression2>
中国石油大学(华东) 计算机应用技术系
Select structure-multi-branch
[Example 4] Enter a college students student ID via keyboard input. Determine and output the students
affiliated college based on the student ID code. The third and fourth digits of the student ID indicate the
college. Assume four possible scenarios: "15" represents the School of New Energy, "07" indicates the School
of Computer Science, "02" denotes the School of Civil Engineering, and other values signify "other colleges".
Sno = input("Please enter the student ID:")
academy = Sno[2:4]
if academy == "15": computational results :
print("This student is from the School of New Energy") Enter the student ID: 2215040201
elif academy == "07": The student is enrolled in the School
of New Energy.
print("This student is from the School of Computer Science")
elif academy == "02":
print("This student is from the School of Stone Engineering")
else:
print("This student is from another college")
中国石油大学(华东) 计算机应用技术系
Select structure-nesting
[Example 5] The subway ticket purchasing regulations are as follows: For rides with 1–4 stops, the fare is 3 yuan
per passenger; for rides with 5–9 stops, the fare is 4 yuan per passenger; for rides with 9 or more stops, the fare is
5 yuan per passenger. Enter the number of stops and passengers, and the system will output the total fare.
中国石油大学(华东) 计算机应用技术系
Loop structure-for statement
Using for in and range together, the number of cycles for is controlled by the "range(n)"
method, and it can be considered that range(n) produces a list from 0 to n-1
[Example 6] Find the factorial of the natural number n.
n = eval(input('Enter any natural number n:'))
factorial = 1
for i in range(1,n+1):
factorial *= i
print(The factorial of '%d: %d'%(n,factorial))
Run result:
Enter any natural number n:13
The factorial of 13 is: 6227020800
中国石油大学(华东) 计算机应用技术系
Loop structure - while statement
The structure of the while statement is:
while<conditions>:
<Statement block>. .
Among them, the traversal structure can be a string, a list, a tuple, a file, or a range() function, etc
[Example 7] Find the greatest common divisor of any two positive integers.
m,n = eval(input('Please enter two positive integers:'))
r=m%n
Run result:
while r!=0:
Please enter two positive integers: 12,24
m=n
The greatest common divisor is: 12
n=r
r=m%n
print('The greatest common divisor is:',n)
中国石油大学(华东) 计算机应用技术系
Loop structure - break and continue statements
中国石油大学(华东) 计算机应用技术系
循环结构——嵌套循环
[Example 8] Design a login program, different usernames and corresponding passwords are
stored in a dictionary, enter the correct username and password to log in, first enter the
username, if the username does not exist or is empty, it will always prompt to enter the correct
username, when the username is correct, it will prompt to enter the password, if the password
does not correspond to the username, then the password is wrong please re-enter, and prompt
several chances. If the password is entered incorrectly more than three times, the program will
be interrupted. When the username and password are successfully entered, it indicates that the
login is successful!
中国石油大学(华东) 计算机应用技术系
Chapter 2 Data Processing Tools
5.2 function
Define functions
The syntax format for function definitions is as follows:
def function name (parameter list):
Function Documentary String (i.e., Function Description)
Functional body
[return return value list]
(1) The function definition begins with the word def reserve, followed by the function identifier name and
parentheses ( ).
(2) The parameter list is placed in parentheses, and can have zero, one or more parameters. The parameters in the
function definition are called formal parameters, or physical parameters for short.
(3) The function content starts with a colon, and the function body format must be indented. Special emphasis is
placed on indentation formatting, otherwise errors will occur.
(5) The "function document string" mainly explains the function of the function, so that programmers can better
read and understand the function, both single and double quotation marks.
(6) When you need to return a value, use the return statement to return the value of the list, otherwise the
function can have no return statement, or only return without returning a list of values, then the function result
returns None.
中国石油大学(华东) 计算机应用技术系
Define parameterless functions
中国石油大学(华东) 计算机应用技术系
Definitions have parameter functions
[Example 10] Calculate the sum of any two numbers.
def add(num1,num2): #The definition has a parameter function add
"Returns the sum of the two parameters"
sum = num1 + num2
return sum #Returns the result of the function calculation
a,b = eval(input('Enter any two numbers:')) #Enter two data
s = add(a,b) #Call the add() function and assign the return result to sum
print('sum =',s)
中国石油大学(华东) 计算机应用技术系
The return value of the function
return can only return a single value, but the value can have multiple elements.
def show():
return [2,4,6,8,10]
print(type(show())) #The type of output returned result
print(show())
Run the result:
<class 'list'> #What is returned is the list type
[2, 4, 6, 8, 10] #The returned list element value
中国石油大学(华东) 计算机应用技术系
The return value of the function
return can only return a single value, but the value can have multiple elements.
def show():
return 2,4,6
print(type(show())) #The type of output returned result
print(show())
Run the result:
<class 'tuple'> #The tuple type is returned
(2, 4, 6) #The value of the tuple element returned
中国石油大学(华东) 计算机应用技术系
Functions - positional parameters and default parameters
def person(name,age,city='Beijing',job='coder'):
print(name,age,city,job)
Default
person('Amely',21) parameters
person('Amely',21,job='teacher')
Run result:
Amely 21 Beijing coder
Amely 21 Beijing teacher
When setting the default parameters, the position parameter is first and the
default parameter is last, otherwise the Python interpreter will give an error.
中国石油大学(华东) 计算机应用技术系
Parameters of functions - variable parameters
Variable parameters mean that the number of parameters passed in is variable,
which can be 0 or any many.
def fun(var,*args):
Run result:
print('var:',var)
print('args:',args)
fun(10,20)
fun(10,20,30)
fun(10,20,30,40)
fun(10,20,30,40,50)
Variable parameters are automatically assembled into a tuple when the
function is called
中国石油大学(华东) 计算机应用技术系
Function's parameters – keyword parameters
Allow 0 or any number of parameters with parameter names to be passed,
and the keyword parameters are automatically assembled into a dictionary
inside the function.
def fun(var,**kw):
print('var:',var)
print('kw:',kw)
fun(10,a=20,b=30,c=40,d=50)
Run the result:
var: 10
kw: {'a': 20, 'b': 30, 'c': 40, 'd': 50}
The order of parameter definitions must be: positional parameters, default parameters, variable
parameters, and keyword parameters.
中国石油大学(华东) 计算机应用技术系
Questions?
中国石油大学(华东)
China University of Petroleum