Python Simple Self-Study Notes
Last updated on July 26, 2025 pm
This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to original Chinese version. I am continuously working to improve the translation.
The split method is used to split a string into multiple small substrings and returns a list
persons = "Mike Jerry Tom"
result = persons.split() # 将字符串使用默认分隔符(空格)拆分成多个小的子字符串
print(result) # 输出:['Mike', 'Jerry', 'Tom']In Python, numbers of string type can be directly cast to int
data = input().split() # 将输入字符串根据空格进行分割,得到数据列表
res = int(data[0])+int(data[1]) # 拿到元素后,进行数据类型转换,累加后赋值给变量 res
print(res)The code inside a try block is attempted; if no error occurs, it executes normally, otherwise the except block catches the exception and executes the exception-handling code
while True:
try:
# 尝试执行这里的程序
except:
# 捕获异常,执行异常处理代码
breakMultiple assignment:
# 1. 多个变量同时赋相同的值
a = b = c = 42 # 变量 a、b 和 c 都被赋予了相同的值
# 2. 多个变量同时赋不同的值
x, y, z = 1, 2, 3 # 变量 x 被赋值为 1,变量 y 被赋值为 2,变量 z 被赋值为 3
# 3. 还可以使用多重赋值获取列表中的值。
a, b = [1, 2] # 将列表中的元素按照顺序赋给 a 和 b,a 的值为 1,b 的值为 2。The range function: generates a sequence of numbers, usage:
range(stop)
range(start, stop)
range(start, stop, step)All are left-closed and right-open
As long as val is a non-zero number, a non-empty string, a non-empty list, etc., it is evaluated as True; otherwise it is False
Python's logical operators: and or not
Ternary operator:
语句1 if 条件表达式 else 语句2Arithmetic operators
a = 10 - 5 # 减法运算,将 10 减去 5,结果为 5
a = 10 + 5 # 加法运算,将 10 和 5 相加,结果为 15
a = 5 * 5 # 乘法运算,将 5 和 5 相乘,结果为 25
a = 10 / 5 # 除法运算,将 10 除以 5,结果为 2.0,Python3 中,除法总是返回浮点数,即便结果是整数
a = 5 // 2 # 整数除法运算,将 5 除以 2,结果为 2(只保留整数部分)
a = 2 ** 2 # 幂运算,2 的 2 次方,即 2^2,结果为 4
a = 10 % 4 # 取余数运算,将 10 除以 4,返回余数,即 2⚠️ In Python3, division always returns a floating-point number
The sum function:
sum(列表,初始值)For example
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total) # 输出 15,因为 1 + 2 + 3 + 4 + 5 = 15The map() function: applies a function to each element of a sequence and returns an iterator containing the results as a new sequence.
It is commonly used for list operations in Python, applying a function to each element of a sequence and returning a new sequence containing the results
map(function, list)Example as follows
string_numbers = ["1", "2", "3", "4", "5"]
# 使用 map(int, list) 将列表中的所有字符串元素全都转换成整数
# 再在外面加一层 list(), 使用 list() 方法将 map 的返回结果转为列表
int_numbers = list(map(int, string_numbers))Common mathematical operations
abs(x)
max(x,y,z, ...)
min(x,y,z, ...)
pow(x,y) #返回 x 的 y 次方
round(x) #四舍五入For the following, you need import math
math.ceil(x): returns the smallest integer greater than or equal to x.math.floor(x): rounds down, returning the largest integer smaller than x.math.pow(x, y): returns x to the power of y; the math module converts the arguments to floating-point numbers.math.sqrt(x): returns the square root of x
Lists:
In Python, lists replace arrays. Compared to arrays, lists are more flexible; they are also used to store an ordered collection of elements, but a list can contain elements of various different types, including integers, floating-point numbers, strings, and even other lists. Moreover, the length of a list is mutable — you can add or remove elements as needed, thereby changing the length of the list.
Common operations:
-
Creating a list: use square brackets
[]or uselist()to create a list.The
list()function can convert other iterable objects into lists, such as strings.my_list = [1, 2, 3, 4, 5] my_list = list() my_str= = "hello" str_list = list(my_str) -
Accessing list elements: use indices to access elements in a list
my_list = [1, 2, 3, 4, 5] first_element = my_list[0] -
Modifying list elements: direct assignment
-
List length: the
len()function -
append(): adds a new element to the end of the list -
insert(index, value): inserts an element at the specified positionmy_list = [1, 2, 3, 4, 5] my_list.insert(0, 6) # [6, 1 ,2 3, 4, 5] -
remove(value): removes the element with valuevalue; if there are multiple, only the first one is deleted. -
pop(index): deletes and returns the element at the specified indexindex.my_list = [1, 2, 3, 4, 5] popped_element = my_list.pop(1) # 删除并返回索引 1 处的元素,现在是 [1, 3, 4, 5] popped_element 是 2 -
index(value): returns the index position of the specified valuevalue; if there are multiple, returns the first one. -
sort() -
reverse() -
list + list means list concatenation
For example,
[1, 2, 3] + [4, 5, 6]==[1, 2, 3, 4, 5, 6]
Slicing: a reference to a contiguous segment of a list
my_list(startIndex: endIndex: step)Note that endIndex is an open interval
- If both the start and end positions are provided, it means slicing from the
startIndexposition to theendIndexposition - If the start position is not provided, i.e.,
list[ : endIndex], it means slicing from the beginning of the list to theendIndexposition - If the end position is not provided, i.e.,
list[startIndex : ], it means slicing from thestartIndexposition to the end of the list - If neither the start nor the end position is provided, i.e.,
list[ : ], it means slicing from the beginning to the end of the list, which is equivalent to the entire list.
Negative indices can also be used: -1 refers to the last element, -2 refers to the second-to-last element, and so on.
Example of initializing a list:
dp = [[0] * (bagweight + 1) for _ in range(n)]
[0] * (bagweight + 1)- Generates a list of length
bagweight + 1 - All elements are
0 - For example,
bagweight = 4→[0, 0, 0, 0, 0]
- Generates a list of length
for _ in range(n)- Loops
ntimes, usually representing the number of rows in the DP table (e.g.,nitems) _means the loop variable is unused
- Loops
[ ... for _ in range(n)]- The outer list comprehension
- Each iteration generates an independent
[0]*(bagweight+1)list - The result is a 2D list of size n×(bagweight+1)
Outputting an array in reverse order:
# 倒序输出元素,每个数之间用空格分隔
for i in range(n - 1, -1, -1):
print(nums[i], end=" ")Outputting every other element
# 遍历顺序从 0 到 n(不包括 n), 步长为 2
for i in range(0, n, 2):
# 输出元素和空格
print(nums[i], end=" ")Sequences are divided into lists, tuples, and strings
- List: wrapped in square brackets
[], with elements separated by commas,. Lists are mutable and support adding, deleting, and modifying operations. - Tuple: wrapped in parentheses
(), with elements separated by commas,. Tuples are immutable; once created, their elements cannot be changed. - String: a collection of characters wrapped in quotes (single or double quotes); the elements are characters, and strings are also immutable.
Some string operations
my_str = "Hello, World!"
length = len(my_str)split(): splits a string into substrings and returns a list; by default, a space is used as the delimiter.join(): joins the strings in a list into a new string; you can specify the joining character, as in the example below.
persons = ["tom", "jerry", "mike"]
text = " ".join(persons)
# 将列表中的字符串以空格连接在一起,相当于 split 的反向操作,"tom jerry mike"replace(): used to replace a specified substring in a string.
str1 = "Hello, World!"
str2 = str1.replace("World", "Python") # 替换 "World" 为 "Python"To control formatting in print(), you can use the format() method
The format() method is typically used for placeholder substitution in strings; placeholders are usually denoted by curly braces {}. You can insert placeholders into a string, then use the format() method to insert the actual values into those placeholders.
number = 3.1415926
# {}是一个占位符,输出结果时会将 format() 参数里的内容替换在{}中,:.2f 表示保留两位小数
formatted_number = "{:.2f}".format(number)
print(formatted_number)String formatting output
In Python, you can use string formatting to insert values into strings to achieve output in a specific format. There are several ways to format strings:
- Using the
%operator for formatting
name = "张三"
age = 20
formatted_string = "姓名:%s,年龄:%d " % (name, age)
print(formatted_string)Using % inserts the following variables name, age one by one into the corresponding placeholders, where %s represents a string, %d represents an integer, and %f represents a floating-point number.
- The string
format()method
The format() method allows you to use placeholders {} to insert values, and uses the arguments of the format() method to provide the values to be inserted, which is very similar to the operator above.
name = "张三"
age = 20
formatted_string = "姓名:{}, 年龄:{}".format(name, age)
print(formatted_string)f-字符串
Python 3.6 and above support f-string, which starts with f followed by a string; expressions in the string are wrapped in curly braces {}, and the computed values of variables or expressions are substituted in.
name = "张三"
age = 20
formatted_string = f"姓名:{name},年龄:{age}"
print(formatted_string)islower(): checks whether all characters in the string are lowercase letters
isupper(): likewise
upper(): converts all characters in the string to uppercase letters. lower() works the same way
Functions
def 函数名(形参列表):
函数体For example:
def max(a,b):
if (a>b):
return a
else:
return bA function that converts a lowercase letter to an uppercase letter:
def changeChar(a):
if 'a'<=a<='z':
a=chr(ord(a)-32)
return a引用
The
-> intyou asked about is a type hint in Python, indicating that the function's return value type isint, i.e., it returns an integer.
✅ Full explanation:
python 复制编辑 def maxVowels(self, s: str, k: int) -> int:The syntax here is Python's function signature annotation, explained part by part below:
Part Meaning selfIndicates this function is a method of a class; the first parameter is the object itself (can only be defined in a class) s: strIndicates the parameter sis a stringk: intIndicates the parameter kis an integer-> intIndicates this function ultimately returns an integer (the return value is of type int)
🔁 A comparison example:
python 复制编辑 def add(a: int, b: int) -> int: return a + bThis means
addis a function that takes two integers and returns an integer.Equivalent to the following in Java:
java 复制编辑 int add(int a, int b) { return a + b; }
⚠️ Notes:
- Type annotations do not enforce type checking (the interpreter does not raise errors), but they can be used by static checking tools such as
mypy,pyright, VSCode hints, etc.- You can also write more complex types, such as
List[str],Optional[int],Dict[str, int], which require importingtyping.
🧠 Summary:
Syntax Meaning 参数名: 类型Annotates the parameter type -> 返回类型Annotates the function's return value type No enforced type checking Relies on tools or developers to maintain it
引用
Yes, variables in Python can also use type annotations, just like function parameters. This is part of Python's Type Hints; although the interpreter does not enforce checking, it is very helpful for you, your IDE, and static checking tools (such as
mypy,pyright).
✅ Basic syntax for variable type annotations:
python 复制编辑 变量名:类型 = 值
🧪 Example:
python 复制编辑 name: str = "Alice" age: int = 30 price: float = 99.99 is_valid: bool = True
🧠 You can also annotate only the type without assigning a value:
python 复制编辑 data: list[int]At this point,
datahas only been declared with a type but has not yet been assigned a value.
Tuples
A tuple is also a sequence; a tuple is an immutable structure, and apart from that, its usage is almost the same as a list.
Creating a tuple tuple is simple: just add elements inside parentheses, with elements separated by commas.
One thing to note is that when a tuple has only one element, you need to add a comma after the element, i.e., (1,).
Tuple unpacking refers to the process of assigning the elements of a tuple to multiple variables respectively. It sounds confusing, but the example is quite simple.
my_tuple = (1,2,3)
# 使用元组拆包将元组的元素分配给多个变量
a, b ,c = my_tupleIn the operation above, we use tuple unpacking to assign each element of the tuple to the variables a, b, and c respectively, allowing quick access to the elements of the tuple.
So the operation a, b = b,a actually constructs a tuple (b, a) from the values of b and a, then uses tuple destructuring ("unpacking") to assign the values in this tuple to a and b respectively, thus completing the swap.
Classes
In a class's code block, we can define variables and functions. Variables defined in a class become attributes of all instances, and all instances can access these variables. Functions can also be defined in a class (called methods), and all instances of the class can also access these methods.
代码
class Person:
# 类中定义一个变量 name, 会成为所有实例的公共属性
name = "Tom"
# 类中也可以定义函数,称之为方法,方法也可以通过该类的实例来访问
def say_hello(self):
print("Hello")
# 创建 Person 的实例
person1 = Person()
person2 = Person()
# 实例可以调用属性
person1.name = "Jerry"
person2.name = "Mike"
# 实例可以调用方法
person1.say_hello()
person2.say_hello()The class's initialization function:
class 类名:
# 公共属性
# init 方法
def __init__(self, 其他参数):
# self 表示实例本身,即实例.name 属性 = 传递的 name 值Using an array as a hash table
Counting the most frequent letter in a string
n=int(input())
for _ in range(n):
s=input()
# 创建一个 长度为 26,元素都为 0 的列表
temp=[0]*26
for c in s:
temp[ord(c)-ord('a')]+=1
maxFreq=0
maxFreqChar=0
for i in range(26):
if temp[i]>maxFreq:
maxFreq=temp[i]
maxFreqChar=i
print(chr(maxFreqChar+ord('a')))
set
In Python, you can use curly braces {} to create a set
# 创建集合
my_set = {1, 2, 3}Alternatively, you can use the set()函数 function to create a set, or convert a list into a set.
my_set1 = set([1, 2, 3])
# 创建空集合
my_set2 = set()The most common uses of sets are checking whether an element is in a set and removing duplicate elements from a set.
To check whether an element is in a set, you can use the in keyword
my_set = {"Tom", "Jerry", "Mike"}
# 判断元素是否在集合中
if "Tom" in my_set:
# 集合用于存储一组不重复的元素,可以自动去重
my_list = [1, 2, 3, 3, 4, 5, 5]
my_set = set(my_list) # 将列表转换为集合,去除重复元素
unique_list = list(my_set) # 将集合转换回列表,此时列表是 [1,2,3,4,5]Similar to operations in mathematics, sets also support union, intersection, and difference.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
u_set = set1 | set2 # 并集,现在集合是{1, 2, 3, 4, 5}
i_set = set1 & set2 # 交集,现在集合是 {3}
d_set = set1 - set2 # 差集,表示存在于集合 1 中,但不存在于集合 2 中的元素,{1, 2}Besides the two common operations above, set also provides some common methods for convenience, mainly including adding, removing, and iterating over set elements.
- Adding elements: use the
add()method to add a single element to a set. - Removing elements: use the
remove()ordiscard()method to remove a specified element from a set. The difference between them is that when removing an element that does not exist in the set,remove()raises an exception, whilediscard()does not. - Set length: use the
len()function to get the number of elements in a set. - Clearing a set: use the
clear()method to remove all elements from a set. - Iterating over a set: use a
forloop to iterate over the elements in a set.
代码
# 创建集合
set1 = {1, 2, 3}
# 向集合添加元素
set1.add(4)
# 遍历集合
for element in set1:
print(element)
# 移除集合元素
set1.remove(3)
# 获取集合长度
print(len(set1))
# 清空集合中的元素
set1.clear()map / dict
In Python, the mapping data structure is usually implemented with dictionaries dict.
A dictionary is also wrapped with {}, each key-value pair is separated by a colon :, and key-value pairs are separated from each other by commas ,. The specific format is as follows:
my_dict = {
"mike", 99,
"tom": 98,
"jerry": 100
}The key data types in a dictionary must be immutable (strings, numbers, tuples, etc.), but the values can be of any data type.
Note: if you directly create a {}, it represents an empty dictionary, not an empty set.
In addition, you can also use the built-in function dict() to create a dictionary. If you want to add key-value pairs to a dictionary, you can do so directly via dict[key] = value.
# 创建一个空字典
my_dict = dict()
# 添加键值对
my_dict["mike"] = 99
my_dict["tom"] = 98
my_dict["jerry"] = 100
# 更新值
my_dict["mike"] = 100
# 访问值
print(my_dict["mike"]) # 100If you want to delete key-value pairs from a dictionary, you can use the del() or clear() methods
del my_dict["mike"] # 删除对应的键值对
my_dict.clear() # 清空字典
del my_dict # 删除字典To check whether a key exists in a dictionary, you also use in; it returns true if the key is in the dictionary, otherwise it returns false.
Strings can also be checked this way to see if they are a substring
if "mike" in my_dict:
print(my_dict["mike"])
else:
print("mike doesn't exist in the dictionary")Iterating over a dictionary requires using for together with dict.items(); the items() method returns a view object of all key-value pairs in the dictionary. This view object can be used to iterate over the key-value pairs in the dictionary.
for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")In addition, you can use dict.keys() and dict.values() to get view objects of all keys and all values in the dictionary, respectively; view objects can be converted to lists via list().
Stack
In Python, a stack is usually implemented by simulating it with a list.
Checking whether the stack is empty: implemented with if not stack; returning true means it is empty
stack = [] # 创建一个空栈
# 入栈
stack.append(1)
stack.append(2)
stack.append(3)
# 出栈
top_element = stack.pop() # 弹出并返回栈顶元素
print(top_element) # 输出 3
# 判断栈是否为空
if not stack:Queue
The queue module in the standard library provides several queue implementations, such as regular queues and priority queues
Therefore, you can use the queue.Queue class to create a queue; however, we can still use a list to simulate a queue implementation.
# 导入 queue 模块
import queue
# 创建一个队列
q = queue.Queue()
# 通过 put() 实现入队操作
q.put(1)
q.put(2)
q.put(3)
# 通过 get() 实现出队操作
item = q.get() # 出队并返回队列中的元素
print(item) # 输出 1Simulating with a list:
queue = []
# 入队操作
queue.append("Tom")
queue.append("Jerry")
queue.append("Mike")
# 出队操作
removed_person = queue.pop(0) # 弹出并返回队列中的第一个元素
# 判断队列是否为空:
if not queue:
print("队列为空")
else:
print(f"队头元素:{queue[0]}")Inheritance
In objects, there are always some operations that are repeated. For example, a Person class has characteristics such as name, height, and age, and has some methods such as walking, eating, and sleeping. If we want to implement a Teacher class, a Teacher is first of all a person and also has the basic characteristics and methods of a person. Should we then implement these characteristics and methods in code? This would inevitably produce some duplicated code.
Therefore, we can use "inheritance" to allow one class to acquire the attributes and methods of other classes. When defining a class, you can specify the parent class (superclass) of the current class in the parentheses after the class name; the subclass can directly inherit all attributes and methods from the parent class, thereby avoiding writing repetitive code. In addition, we can also extend the subclass.
Suppose we have a shape class Shape, which has two attributes and one method; the attributes are color and type, and the method calculates the area of the shape
class Shape:
# 包含颜色和类型两个属性
def __init__(self, shape_type, color):
self.type = shape_type
self.color = color
# 计算图形面积的方法
def calculate_area(self):
# pass 表示空语句,不需要执行任何操作
pass
shape = Shape('shape', 'white')We also need a class for circles, which inherits from the Shape class
# 传入 Shape, 表示基础自 Shape 类
class Circle(Shape):
def __init__(self, shape_type, color, radius):
super().__init__(shape_type, color)
self.radius = radius
# 计算圆的面积
def calculate_area(self):
return 3.14 * self.radius * self.radius
circle = Circle('circle', 'white', 10)
# 计算圆的面积
circle.calculate_area()In the example code above, the shape class has two attributes and one method, and the circle class adds the radius attribute on top of the shape class.
super().__init()The parent class and the subclass share some common attributes. When overriding the subclass, in order to omit repetitive code, you can use super() to dynamically get the parent class of the current class and call the parent class's __init__() method to initialize the attributes defined in the parent class.
Both the subclass and the parent class have the calculate_area method; this is called method overriding, and the subclass will call its own method rather than the parent class's method. If an object of the subclass calls a method and finds that this method is not provided, it will look for it in the parent class of the current object; if the parent class has it, it directly calls the parent class's method; if not, it looks in the parent class's parent class. It is like when a father and a son both own the same thing, they will prefer to use their own; only when they find they don't have it will they use the inherited method.
Polymorphism
Polymorphism is often closely tied to inheritance; it allows different objects to respond differently to method calls. You can use a base class to define generic code, and then provide specific implementations in derived classes, so that different methods are called when the method is invoked, as in the example below:
代码
class Shape:
# 基类的计算面积的方法
def calculate_area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
# Circle 类的计算面积的方法
def calculate_area(self):
return 3.14 * self.radius * self.radius
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
# Rectangle 类的计算面积的方法
def calculate_area(self):
return self.width * self.height
# 创建不同类型的图形对象
circle = Circle(2)
rectangle = Rectangle(4, 3)
# 存放图形对象的列表
shapes = [circle, rectangle]
# 计算面积
for shape in shapes:
# 列表中的每个元素都调用计算面积的方法
area = shape.calculate_area()
# 输出面积
print(f"Area: {area:.2f}")In the code example above, the base class Shape implements the calculate_area method, and the two derived classes Circle and Rectangle override the calculate_area method with different calculation logic. Then we create a list shapes containing shape objects of different types, and loop through the list calling the calculate_area method. Although the method names are the same, the method actually called is dynamically determined based on the object's type — this is exactly the concept of polymorphism.
This is a very commonly used iteration pattern in Python, using
enumerate()to obtain both the index and the value of each element at the same time. Let's explain this line step by step:for i, x in enumerate(nums):
🧠 Breakdown:
Part Meaning numsAn iterable object (such as a list) enumerate(nums)Converts numsinto an iterator of(索引, 元素)pairsfor i, x in ...Obtains the index iand the element valuexof each item at the same time