0% found this document useful (0 votes)
2 views84 pages

Chapter 2 - Data Processing Tools (Python Basics)

Uploaded by

captaninam
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views84 pages

Chapter 2 - Data Processing Tools (Python Basics)

Uploaded by

captaninam
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

中国石油大学(华东)

China University of Petroleum

Chapter Two Data Processing Tools

Lecturer: Wang Xuerui

计算机应用技术系
Chapter Two Data Processing Tools
1 Tool Introduction
Contents
2 Python language development environment 目录

3 Simple data processing in the Python language

3.1 Variables and


3.1 data types

3.2 Operational character

3.3 3.3
Input and Output

3.4 Common built-in


3.4 functions
Variable
All data in Python is an "Variable", and every Variable has three core characteristics:
identity (id), type (type), and value (value).
Identity (memory address) can be queried with the id() function, type can be queried
with the type() function, and the value can be seen by printing it with print.
>>> id(25) # Check the memory address of the integer object 25
1396535056
>>> id('hello') # Check the memory address of the string object 'hello'
1928617652040
>>> type(25) # Check the type of the object 25
<class 'int'> # int is the type name of integer data objects
>>> type('hello') # Check the type of the object 'hello'
<class 'str'> # str is the type name of string data objects
中国石油大学(华东) 计算机应用技术系
Variable
A "variable" and a "number (object)" establish a corresponding
relationship: a variable connects to an object through reference.
>>> x = 3 # Assign the integer object 3 to the variable x; x can now
# access the integer 3
>>>x # Check the value of the object referenced by variable x
3
>>> x = 5 # The value of variable x is modified to reference the integer
# 5; x can now access the integer 5
>>>x # Check the value of the object referenced by variable x after
# modification
5
中国石油大学(华东) 计算机应用技术系
Variable
Naming Rules for Variables in Python

➢ Variable names can only be any combination of letters, numbers, or underscores.


➢ The first character of a variable name cannot be a number.
➢ No spaces are allowed in the middle of a variable name.
➢ There is no limit to the length of a variable name.
➢ Variable names are case-sensitive.
➢ Keywords cannot be declared as variable names.

中国石油大学(华东) 计算机应用技术系
Data Types

中国石油大学(华东) 计算机应用技术系
Arithmetic operators

operator description instance

+ 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

* multiply operation The result of 2×10 is 20


The result for 20/4 is 5.0, and the result for 3/4 is 0.75 (the
/ Division operation
result is a floating-point number).

% modular arithmetic The result of 7%3 is 1

** Power operation The result of 2**3 is 8

// 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

operator description instance

== equal to 10 == 20 Result is False

!= not equal to 10! = 20 Result is True

> greater than 10> 20 Result is False

< less-than 10 <20 Result is True

>= be equal or greater than 10>= 20 Result is False

<= less than or equal to 10 <= 20 Result is True

中国石油大学(华东) 计算机应用技术系
Logical operator

operator instance explain

and x and y If x is False, do not calculate y; the result is x. Otherwise, the result is y.

or x or y If x is True, the result is x without calculating y; otherwise, the result is y.

not not x If x is True, the result is False; if x is False, the result is True.

Note the short-circuit phenomenon of logical operators AND and OR

中国石油大学(华东) 计算机应用技术系
Member operator
Used to determine whether an element is in a sequence, such as a string, list, or tuple.

operator instance explain


Find the value of x in y. If true, return true; otherwise,
in x in y
return false.
The value of x is not found in y, so the result is True.
not in x not in y
Otherwise, the result is False.
>>>'a' not in 'abc'
>>>'a' in 'abc'
False
True
>>> 'ac' not in 'abcd'
>>>'ac' in 'abcd'
True
False

中国石油大学(华东) 计算机应用技术系
Formatted output
1) Format using the% symbol
>>> x,y=3,4

>>> print("%3d,%.2f"% (x,y))


2) Format strings using the format method
>>> x,y=3,4
>>> print("{: 3d} ,{: .2f}" .format (x,y))

中国石油大学(华东) 计算机应用技术系
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.

map(type, input().split(',')): Input data, separated by commas


map(type, input().split(' ')): Input data, separated by spaces

中国石油大学(华东) 计算机应用技术系
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

Returns the quotient remainder of x divided by y (x//y, x%y), with the


divmod ( x,y )
result as a tuple.
The return value is (x**y)%z, where [...] indicates that the parameter can
pow( x,y[,z])
be omitted, i.e., pow(x, y).
Returns the rounded value of x with ndigits decimal places. round(x)
round(x[, ndigits])
returns the rounded integer value.

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.

float(x) Convert x to a floating-point number. x can be an integer 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.

chr (x) Convert x to a single-character string. x is an ASCII integer.

bin(x) Convert x to a binary string starting with ‘0b’

oct (x) Convert x to an octal string starting with ‘0o’

hex(x) Convert x to a hexadecimal string starting with ‘0x’

bool (x) Convert x to the Boolean value True or False

中国石油大学(华东) 计算机应用技术系
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

Returns the modulo of x and y, with the result


[Link] ( x,y ) x%y
as a floating-point number.
[Link](10,4) returns 2.0

[Link]([ x,y,…]) x+y+ … Accurate floating-point sum [Link]([1.0,2.0,3.0]) returns 6.0

Round up to the nearest integer not less than


[Link](x) 𝑥
x
[Link] (3.2) returns 4

Round down to the nearest integer not


[Link] (x) 𝑥
greater than x
[Link] (3.2) returns 3

Returns the greatest common divisor of a and


[Link] (a,b) b
[Link](12,21) returns 3

[Link] ( x,y ) x𝑦 Returns x to the y-th power [Link](2,3) returns 8.0

Returns the x-th power of e, where e is the


[Link] (x) 𝑒𝑥
natural logarithm.
[Link](2) returns 7.38905609893065

[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

Returns the cosine function value of x, where


[Link] (x) cos 𝑥
x is in radians.
[Link]([Link]) returns-1.0

中国石油大学(华东) 计算机应用技术系
Chapter 2 Data Processing Tools

4 Multi-data Processing in Python Language Contents


目录
4.1 String operations

4.2 List operations

4.3 Operation on tuples

4.4 Dictionary operations


String operations

• 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]])

Here, sub denotes the element to be searched;

start indicates the starting search position;

The end signal indicates the termination of the search position

>>> s=‘Python is funny.’


>>> [Link] (‘n’,6,13)
12 # The index value of the character n found in the range [6,13] is 12, which is the
second character‘n’.

中国石油大学(华东) 计算机应用技术系
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.

>>> s=‘Python is funny.’


>>> [Link] (‘n’,6,13)
12 # The index value of the character‘n’found in the range [6,13] is 12
>>> [Link](‘py’) #Search for substring‘py’
-1 #Output-1, indicating the substring ‘py’ was not found

中国石油大学(华东) 计算机应用技术系
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.

>>> name = " Hello,Python"


>>> len(name) #Calculates the length of the string name
12

中国石油大学(华东) 计算机应用技术系
String operations

• Connection operation — Use “+” to join strings

>>> year =‘2023’ # Define a string to store the year year


>>> month =‘03’ # Define a string to store the month month
>>> year + month
‘202303’ #String after concatenation
>>> year + ‘年’+ month + ‘月’ #Use operators to join multiple string data
‘2023 March’ #connected string

中国石油大学(华东) 计算机应用技术系
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

• Connection operation — Use the operator "*" to connect string replication

>>> 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]() #Split the string str using default delimiters

[‘[Link]’] #Returns the entire string as an element of a list

>>> [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

'upc' #List elements that are subscripted with 1 after splitting

中国石油大学(华东) 计算机应用技术系
String operations
• Statistical operations

count() calculates the frequency of a specific character in a string

Its format is: [Link](sub, [start, [end]]).

among ,

The parameter sub specifies the substring to be counted.

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

>>> Winter_Games = ‘Together for a Shared Future.’

>>> Winter_Games.count(‘e’) #Counts occurrences of ‘e’ in the string

>>> Winter_Games .count(‘e’,5)

中国石油大学(华东) 计算机应用技术系
Chapter 2 Data Processing Tools

4 Multi-data Processing in Python Language Contents


目录
4.1 String operations

4.2 List operations

4.3 Operation on tuples

4.4 Dictionary operations


List operations
• Create list
Simply enclose the comma-separated data items in square brackets.

>>> lt = [] #Create empty list lt


>>> ls = [‘hello’, [1,2],3.5, [‘a’, ‘b’]] # Create a list with different element types ls
>>> ls #View contents in the list
[‘hello’, [1, 2], 3.5, [‘a’, ‘b’]]

中国石油大学(华东) 计算机应用技术系
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

>>> rlist = [10.4,10.7, [‘a’, ‘b’], 100, ‘red’] #Create list


>>> rlist[-3] #Accesses the element at index-3, starting from the right
[‘a’,’b’]
>>> rlist[1:3] # Slice access to list elements from rlist[1] to rlist[2]
[10.7, [‘a’,’b’]]
>>> lr = rlist[:-1]
>>> lr #View list content
[10.4, 10.7, [‘a’,’b’],100]

中国石油大学(华东) 计算机应用技术系
List operations

• Add operation — Slice method


The slicing method not only extracts list elements but also allows adding new elements at
any position in the list.

>>> ls1 = [104,107,109,113,118] #Create list


>>> len(ls1) #View the length of the list ls1
5
>>> ls1[ len(ls1):]
[] # Extract all subsequent list elements starting from index len (ls1), returning an
empty list if no elements are found

中国石油大学(华东) 计算机应用技术系
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)

>>> ls2 = [1,2,3]


Note: Added elements retain their original
>>> [Link]( ‘abc’ )
structural type in the list, and only one
>>> ls2 element can be added at a time.
[1, 2, 3, ‘abc’ ]
>>> [Link]([‘a’,3.14])
>>> ls2
[1, 2, 3, ‘abc’ , [‘a’, 3.14] ]

中国石油大学(华东) 计算机应用技术系
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.

>>> ls4 = [‘data’,123,10.5]


>>> [Link](0,2023)
>>> ls4
[ 2023, ‘data’, 123, 10.5]
>>> [Link](2,[‘python’,12])
>>> ls4
[2023, ‘data’, [‘python’, 12], 123, 10.5]

中国石油大学(华东) 计算机应用技术系
List operations
• Delete operations — del, pop()

>>> slist = [‘a’,1, ‘python’, [2.5,3.5],2023,4] # Create a list object


>>> del slist[1:4] #Delete specific slice elements from the list [1, ‘python’,
[2.5,3.5]]
>>> slist #View the list after deleting elements
[‘a’,2023,4]
>>> [Link]() # Removes the last element from the list and returns its value
4
>>> year= [Link] (1) #Remove the element value with index 1 and return it to the
variable year
>>> year #View the value of year
2023

中国石油大学(华东) 计算机应用技术系
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

>>> mlist = [1,2,3,4,5]


>>> mlist[3] = ‘python’ # Modify the element value and type of index 3
>>> mlist
[1,2,3, ‘python’, 5] #Modified list content
>>> mlist[1:3] = [‘funny’,3.14]
>>> mlist
[1, ‘funny’, 3.14, ‘python’, 5]

中国石油大学(华东) 计算机应用技术系
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

4 Multi-data Processing in Python Language Contents


目录
4.1 String operations

4.2 List operations

4.3 Operation on tuples

4.4 Dictionary operations


Operation on tuples
• Create tuple

>>> stuple = () #Create an empty tuple


>>> rtuple = (1, ‘python’, 19.9, [‘a’, ‘b’]) # parentheses can be omitted
>>> rtuple #View tuple content
(1, ‘python’, 19.9, [‘a’, ‘b’])
>>> tuple(‘I love you, China’) #tuple() function converts strings into tuples
('I', ' ', 'l', 'o', 'v', 'e', ' ', 'y', 'o', 'u', ',', ' ', 'C', 'h', 'i', 'n', 'a')
>>> tuple([1,2,3]) # The tuple() function converts a list into a tuple
(1, 2, 3)

中国石油大学(华东) 计算机应用技术系
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

4 Multi-data Processing in Python Language Contents


目录
4.1 String operations

4.2 List operations

4.3 Operation on tuples

4.4 Dictionary operations


Dictionary operations

• 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

>>> Stu = {‘No’:’1001’,’Name’:’Cindy’,’age’:18,’score’:[100,98]}


>>> Stu[‘Name’] #Find the value ‘Cindy’ corresponding to the key ‘Name’
‘Cindy’
>>> Stu[‘score’] #Find the value corresponding to the key ‘score’ [100,98]
[100, 98]

中国石油大学(华东) 计算机应用技术系
Dictionary operations
• retouching operation

>>> Stu = {‘No’:1001,’Name’:’Cindy’,’age’:18}


>>> Stu[‘age’] = 28 #Set the value of the ‘age’ key to 28
>>> Stu
{‘No’: 1001, ‘Name’: ‘Cindy’, ‘age’: 28}
>>> Stu[‘address’] = ‘Shandong’ #key ‘address’ does not exist in the original dictionary
>>> Stu
{‘No’: 1001, ‘Name’: ‘Cindy’, ‘age’: 28, ‘address’: ‘Shandong’ }

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

>>> colors = {1: ‘red’,2: ‘blue’,3: ‘green’,4: ‘purple’}


>>> del colors[1] #Delete key with value pair {1: ‘red’}
>>> colors
{2: ‘blue’, 3: ‘green’, 4: ‘purple’}
>>> del colors #Delete dictionary colors

中国石油大学(华东) 计算机应用技术系
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 Python Programming Language Contents


目录

5.1 Program control structure

5.2 function
Sequential structure

Basic methods of program writing IPO


[1] Analyze the data to be processed in the problem and input it (using the input function)
[2] Data Processing (Use of Multiple Operators and Python Language Expressions)
[3] Output result (using the print function)

中国石油大学(华东) 计算机应用技术系
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>

Sno = input("Please enter the student ID:")


academy = Sno[2:4]
print("This student {} is enrolled in the School of Computer Science." format("Yes" if
academy == 07 else "No"))
computational results :
Enter student ID: 2215040101
The student is not enrolled in the School of Computer Science.

中国石油大学(华东) 计算机应用技术系
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.

m, n = map(int, input(‘Please enter the number of stations and people:’).split(‘,’))


if m <= 4:
pay = 3 * n computational results :
else : Enter the number of stations and people: 5,3
if m <= 9: Accounts Payable: 12
pay = 4 * n
else :
pay = 5 * n
print(‘Accounts Payable:’, pay)
中国石油大学(华东) 计算机应用技术系
Loop structure-for statement
The structure of the for statement is:
for <loop variable> in <iteration structure>:
<Statement Block>
The traversal structure can include strings, lists, tuples, files, or range() functions.

for animal in ["dog", "cat", "mouse"]:


print("{} is an animal".format (animal))
computational results :
dog is an animal
cat is an animal
mouse is an animal

中国石油大学(华东) 计算机应用技术系
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

for num in range(1,6): for num in range(1,6):


if num % 2 == 0: if num % 2 == 0:
break continue
print(num, end = ' ') print(num, end = ' ')
Run the result: Run the result:
1 135

中国石油大学(华东) 计算机应用技术系
循环结构——嵌套循环
[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 Python language programming Contents


目录

5.1 Program control structure

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

[Example 9] Print the first 10 natural numbers.

def printNum(): #Define the parameterless function printNum()

"Print the first 10 natural numbers" #Function documentary string

for i in range(1,11): #Traverse the list of integers in the loop 1~10

print(i,end=' ') #Output the first 10 natural numbers

printNum() #Call the function printNum()

中国石油大学(华东) 计算机应用技术系
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

You might also like