Bootstrap

大模型学习-Python-基础语法

大模型学习-Python-基础语法

Python 不用分号结束语句;不用花括号区分代码块作用域而用缩进表示;用冒号转接所属代码块。
小括号可以连接多行代码作为一条语句

score = 87
level = ('D' if score < 60 else
		'C' if score < 70 else
		'B' if score < 80 else
		'A' if score < 90 else
		'S' if score <= 100 else
		'not a good value')
print(level)

1. 变量与数据类型

变量

在Python中,变量不需要事先声明,赋值即可使用。变量名称可以包含字母、数字和下划线,但不能以数字开头。

# 变量赋值示例  
name = "Alice"  
age = 30  
height = 1.75

数据类型

Python有几种内置的基本数据类型,每种都有其特定的用途和操作方式。

类型说明示例
整数 (int)表示整数值,包括正数、负数和零。没有取值范围,可以无限大。c++ 中区分 char short int long,且每个类型都有取值范围。num = 123
浮点数 (float)表示带有小数部分的实数值。通常是双精度浮点数,占用64位。c++ 中区分单精度与双精度。pi = 3.14159
复数 (complex)表示复数,包含实部和虚部。可以直接用实部+虚部的方式表示。c++ 中需要通过 std::complex 定义。c = 1+2j
布尔值 (bool)表示真值或假值。是整数的子类型,True 等价于 1,False 等价于 0。取值为True 与 False。c++ 中取值为 true 与 false。is_admin = True
字符串 (str)有序、不可变的字符序列。序列的一种,支持切片。c++ 中字符串变量可修改,字符串常量不可修改。greet = ‘Hello, World!’
列表 (list)有序、可变、允许重复的集合。序列的一种,支持切片。可以存储任何数据类型。c++ 中不存在此类可以存放不同类型数据的容器。fruits = [‘apple’, ‘banana’, ‘orange’]
元组 (tuple)有序、不可变、允许重复的集合。可以存储任何数据类型。c++ 中不存在此类可以存放不同类型数据的容器。colors = (‘red’, ‘green’, ‘blue’)
字典 (dict)无序、可变的键值对集合。键必须是唯一的,值可以是任何数据类型。c++ 中不存在此类可以存放不同类型数据的容器。person = {‘name’: ‘Bob’, ‘age’: 30, ‘city’: ‘New York’}
集合 (set 和 frozenset)无序、不可重复的唯一元素集合。可以存储任何数据类型。c++ 中不存在此类可以存放不同类型数据的容器。unique_numbers = {1, 2, 3, 3, 4}
None表示没有值或不存在的对象。result = None
序列

序列是一种可以存储多个值的数据结构。序列并非时一种内置数据类型,而是一种结构统称。序列类型的主要特征是它们是有序的,可以通过索引访问元素,并且具有某些通用的操作和方法。Python中的序列支持迭代、连接、切片,以及重复等操作。
列表是一种可变序列,元组与字符串是不可变序列。序列包含如下运算:

运算符or关键字说明
+序列拼接
*序列拷贝
del用于删除对象,也可以删除序列中的元素。
in / not in判断某个元素是否包含在序列中。
is / is not同一性运算符,判断对象的id值是否相等,从而判断是否是同一个对象。

序列切片语法:

s = "python"
t = (1,2,3,4,5)
l = [1,2,3,4,5]

# 切片方式获取序列全部元素
s[:] # 输出: 'python'
t[:] # 输出: (1, 2, 3, 4, 5)
l[:] # 输出: [1, 2, 3, 4, 5]

# 切片方式获取序列的部分元素
s[1:] # 输出: 'ython'
s[1:3] # 输出: 'yt'
s[0:5:2] # 输出: 'pto'
t[1:] # 输出: (2, 3, 4, 5)
t[1:3] # 输出: (2, 3)
t[0:5:2] # 输出: (1, 3, 5)
l[1:] # 输出: [2, 3, 4, 5]
l[1:2] # 输出: [2]
l[1:5:2] # 输出: [2, 4]

# 切片方式翻转序列
s[::-1] # 输出: 'nohtyp'
t[::-1] # 输出: (5, 4, 3, 2, 1)
l[::-1] # 输出: [5, 4, 3, 2, 1]

# 切片方式修改序列,字符串与元组为不可变序列,不可修改
s[0:3]="" # 报错,不可修改序列: 
Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    s[0:3]=""
TypeError: 'str' object does not support item assignment
t[0:3]=() # 报错,不可修改序列: 
Traceback (most recent call last):
  File "<pyshell#53>", line 1, in <module>
    t[0:3]=()
TypeError: 'tuple' object does not support item assignment
l[0:3] = []
l # 输出: [4, 5]

序列的打包与解包:

s = "abc" # 打包
t = (1,2,3) # 打包
l = [1,2,3] # 打包
s1,s2,s3 = s # 解包
print(s1,s2,s3) # 输出: a b c
t1,t2,t3 = t # 解包
print(t1,t2,t3) # 输出: 1 2 3
l1,l2,l3 = l # 解包
print(l1,l2,l3) # 输出: 1 2 3

s1,s2,s3,s4 = s # 报错:
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\test.py", line 11, in <module>
    s1,s2,s3,s4 = s
ValueError: not enough values to unpack (expected 4, got 3)

s1,s2 = s # 报错:
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\test.py", line 11, in <module>
    s1,s2 = s
ValueError: too many values to unpack (expected 2)

s1,*s2 = s
print(s1,s2) # 输出: a ['b', 'c']

序列处理函数示例:

# 相互转换函数 list()、tuple()、str() 可以转换成对应的类型。
list("python") # 输出: ['p', 'y', 't', 'h', 'o', 'n']
list((1,2,3,4,5)) # 输出: [1, 2, 3, 4, 5]
tuple("python") # 输出: ('p', 'y', 't', 'h', 'o', 'n')
tuple([1, 2, 3, 4, 5]) # 输出: (1, 2, 3, 4, 5)
str([1, 2, 3, 4, 5]) # 输出: '[1, 2, 3, 4, 5]'
str((1, 2, 3, 4, 5)) # 输出: '(1, 2, 3, 4, 5)'

# 计算函数 min()、max() 函数计算序列中的最大最小值。
s = [1, 2, 3, 3, 5]
min(s) # 输出: 1
max(s) # 输出: 5
s = []
min(s) # 报错
max(s) # 报错:
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    min(s)
ValueError: min() arg is an empty sequence
min(s, default="null") # 输出: 'null'
max(s, default="null") # 输出: 'null'
min(1,2,0,3) # 输出: 0
max(1,2,0,3) # 输出: 3

# 长度统计函数
len("python") # 输出: 6
len(range(2**100)) # 报错,序列太长
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    len(range(2**100))
OverflowError: Python int too large to convert to C ssize_t

# 求和函数
sum([1,2,3,4,5]) # 输出: 15
sum([1,2,3,4,5],100) # 输出: 115

# 排序函数
s = [1, 0, 2, 1, 3]
sorted(s) # 输出: [0, 1, 1, 2, 3]
sorted(s, reverse=True) # 输出: [3, 2, 1, 1, 0]
s # 输出: [1, 0, 2, 1, 3]
s = ["apple", "pen", "hello", "good"]
sorted(s) # 输出: ['apple', 'good', 'hello', 'pen']
sorted(s, key=len) # 输出: ['pen', 'good', 'apple', 'hello']
sorted("python") # 输出: ['h', 'n', 'o', 'p', 't', 'y']
sorted((1,0,2,1,3)) # 输出: [0, 1, 1, 2, 3]
reversed([1,0,2,1,3]) # 输出: <list_reverseiterator object at 0x00000221262A9C00>
list(reversed([1,0,2,1,3])) # 输出: [3, 1, 2, 0, 1]
list(reversed("python")) # 输出: ['n', 'o', 'h', 't', 'y', 'p']
list(reversed(range(0,5))) # 输出: [4, 3, 2, 1, 0]

# 判断函数 all() any()
all([1,0]) # 输出: False
all([1,2]) # 输出: True
any([0,0]) # 输出: False
any([0,1]) # 输出: True

# 枚举函数
seasons = ["Spring", "Summer", "Fall", "Winter"]
enumerate(seasons) # 输出: <enumerate object at 0x000002212625ABC0>
list(enumerate(seasons)) # 输出: [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

# 聚合函数
x = [1,2,3]
y = "abcde"
zip(x,y) # 输出: <zip object at 0x000002212450AEC0>
list(zip(x,y)) # 输出: [(1, 'a'), (2, 'b'), (3, 'c')]
import itertools
list(itertools.zip_longest(x,y)) # 输出: [(1, 'a'), (2, 'b'), (3, 'c'), (None, 'd'), (None, 'e')]

# 元素计算函数 map() filter()
map(ord, "python") # 输出: <map object at 0x00000221262ABD00>
list(map(ord, "python")) # 输出: [112, 121, 116, 104, 111, 110]
list(map(pow,[1,2,3],[2,3,4])) # 输出: [1, 8, 81]
list(filter(str.islower,"Python")) # 输出: ['y', 't', 'h', 'o', 'n']

# 获取迭代器 iter() next()
x = iter("he")    
type(x) # 输出: <class 'str_iterator'>
next(x) # 输出: 'h'
next(x) # 输出: 'e'
next(x) # 迭代完成,会报错 
Traceback (most recent call last):
  File "<pyshell#89>", line 1, in <module>
    next(x)
StopIteration

x = iter("he")
next(x, "is empty") # 输出: 'h'
next(x, "is empty") # 输出: 'e'
next(x, "is empty") # 迭代完成,输出: 'is empty'
字符串

有序、不可变的字符序列。因为是序列所以支持切片。因为不可变所以不可以增、删、改,只能进行查操作。所有目标是对字符串进行修改的操作都是输出新的字符串,而不是在原始字符串基础上进行修改。

字符串处理-大小写转换

casefold() 比 lower() 更严格,特别是在处理德语 ẞ 时,它会将大写的 ẞ 转换为小写的 ‘ss’。

函数说明
capitalize()将字符串的第一个字符转换为大写,其他字符转换为小写。
title()将字符串中的每个单词的首字母转换为大写。
swapcase()将字符串中所有大写字母转换为小写,小写字母转换为大写。
upper()将字符串中的所有小写字母转换为大写。
lower()将字符串中的所有大写字母转换为小写。
casefold()将字符串转换为小写,并去除某些 Unicode 字符的区别(比 lower() 更严格)
# capitalize() 将字符串的第一个字符转换为大写,其他字符转换为小写。
s = "hello world"  
print(s.capitalize())  # 输出: Hello world  

# title() 将字符串中的每个单词的首字母转换为大写。
s = "hello world"  
print(s.title())  # 输出: Hello World  

# swapcase() 将字符串中所有大写字母转换为小写,小写字母转换为大写。
s = "Hello World"  
print(s.swapcase())  # 输出: hELLO wORLD  

# upper() 将字符串中的所有小写字母转换为大写。
s = "hello world"  
print(s.upper())  # 输出: HELLO WORLD  

# lower() 将字符串中的所有大写字母转换为小写。
s = "Hello World"  
print(s.lower())  # 输出: hello world 

# casefold()将字符串转换为小写,并去除某些 Unicode 字符的区别(比 lower() 更严格)。
s = "HELLO WORLD"  
print(s.casefold())  # 输出: hello world 
s = "ẞ"  
print(s.lower())  # 输出: 'ß'(小写 sharp S)  
print(s.casefold())  # 输出: 'ss'(更严格的大小写折叠)
字符串处理-查找
函数说明
find(sub[, start[, end]])查找子串 sub 在字符串中第一次出现的位置。如果未找到,返回 -1。
rfind(sub[, start[, end]])从右往左查找子串 sub 在字符串中第一次出现的位置。如果未找到,返回 -1。
index(sub[, start[, end]])查找子串 sub 在字符串中第一次出现的位置。如果未找到,抛出 ValueError。
rindex(sub[, start[, end]])从右往左查找子串 sub 在字符串中第一次出现的位置。如果未找到,抛出 ValueError。
count(sub[, start[, end]])返回子串 sub 在字符串中出现的次数。
# find(sub[, start[, end]]) 查找子串 sub 在字符串中第一次出现的位置。如果未找到,返回 -1。
s = "hello world"  
print(s.find("world"))  # 输出: 6  
print(s.find("python")) # 输出: -1  

# index(sub[, start[, end]]) 查找子串 sub 在字符串中第一次出现的位置。如果未找到,抛出 ValueError。
s = "hello world"  
print(s.index("world"))  # 输出: 6  
# print(s.index("python")) # 抛出 ValueError  

# count(sub[, start[, end]]) 返回子串 sub 在字符串中出现的次数。
s = "banana"  
print(s.count("a"))  # 输出: 3
字符串处理-前后缀处理(去空格)
函数说明
strip([chars])删除字符串两端的空白字符(或指定字符 chars)。
lstrip([chars])删除字符串左端的空白字符(或指定字符 chars)。
rstrip([chars])删除字符串右端的空白字符(或指定字符 chars)。
removeprefix([chars])删除前缀指定字符。
removesuffix([chars])删除后缀指定字符。
# strip([chars]) 删除字符串两端的空白字符(或指定字符 chars)。
s = "   hello world   "  
print(s.strip())  # 输出: hello world  
s = "!!!hello world!!!"  
print(s.strip("!"))  # 输出: hello world

# lstrip([chars]) 删除字符串左端的空白字符(或指定字符 chars)。
s = "   hello world"  
print(s.lstrip())  # 输出: hello world

# rstrip([chars]) 删除字符串右端的空白字符(或指定字符 chars)。
s = "hello world   "  
print(s.rstrip())  # 输出: hello world

# removeprefix([chars]) 删除前缀指定字符。
# removesuffix([chars]) 删除后缀指定字符。
s = "www.python.com"
print(s.removeprefix("www.")  # 输出: python.com
print(s.removesuffix(".com")  # 输出: www.python
字符串处理-分割与拼接

join(iterable) 将可迭代对象 iterable 中的所有元素连接成一个字符串。效率比字符串 + 运算更高,在大数据处理时差异明显。

函数说明
split(sep=None[, maxsplit])将字符串按分隔符 sep 分割成子字符串列表。如果 sep 为 None,则按空白字符分割。
rsplit(sep=None[, maxsplit])从右往左开始分割,将字符串按分隔符 sep 分割成子字符串列表。如果 sep 为 None,则按空白字符分割。
splitlines()将字符串按行分割成子字符串列表。
partition(sep)将字符串按分隔符 sep 分割为三部分:左侧、分隔符、右侧。如果未找到分隔符,返回 (原字符串, ‘’, ‘’)。
rpartition(sep)从右往左开始分割,将字符串按分隔符 sep 分割为三部分:左侧、分隔符、右侧。如果未找到分隔符,返回 (原字符串, ‘’, ‘’)。
join(iterable)将可迭代对象 iterable 中的所有元素连接成一个字符串。
# split(sep=None[, maxsplit]) 将字符串按分隔符 sep 分割成子字符串列表。如果 sep 为 None,则按空白字符分割。
s = "apple,banana,cherry"  
print(s.split(","))  # 输出: ['apple', 'banana', 'cherry']  
s = "hello   world"  
print(s.split())  # 输出: ['hello', 'world']

# rsplit(sep=None[, maxsplit]) 类似 str.split(),但从右侧开始分割。
s = "apple,banana,cherry"  
print(s.rsplit(","))  # 输出: ['apple', 'banana', 'cherry']

# splitlines() 将字符串按行分割成子字符串列表。
s = "apple\nbanana\ncherry"  
print(s.splitlines())  # 输出: ['apple', 'banana', 'cherry']
s = "apple\r\nbanana\r\ncherry"  
print(s.splitlines())  # 输出: ['apple', 'banana', 'cherry']
s = "apple\rbanana\rcherry"  
print(s.splitlines())  # 输出: ['apple', 'banana', 'cherry']
s = "apple\rbanana\rcherry"  
print(s.splitlines(True))  # 输出: ['apple\r', 'banana\r', 'cherry']

# partition(sep) 将字符串按分隔符 sep 分割为三部分:左侧、分隔符、右侧。如果未找到分隔符,返回 (原字符串, '', '')。
s = "apple,banana,cherry"  
print(s.partition(","))  # 输出: ('apple', ',', 'banana,cherry')  
s = "hello world"  
print(s.partition(","))  # 输出: ('hello world', '', '')

# rpartition(sep) 类似 str.partition(),但从右侧开始分割。
s = "apple,banana,cherry"  
print(s.rpartition(","))  # 输出: ('apple', ',', 'banana,cherry')  
s = "hello world"  
print(s.rpartition(","))  # 输出: ('hello world', '', '')

# join(iterable) 将可迭代对象 iterable 中的所有元素连接成一个字符串。
s = "-"  
print(s.join(["1", "2", "3"]))  # 输出: 1-2-3  
字符串处理-内容判断
函数说明
startswith(prefix[, start[, end]])检查字符串是否以 prefix 开头。
endswith(suffix[, start[, end]])检查字符串是否以 suffix 结束。
isalpha()检查字符串是否仅由字母组成。
isdigit()检查字符串是否仅由数字组成。
islower()检查字符串是否所有字母均为小写。
isupper()检查字符串是否所有字母均为大写。
isspace()检查字符串是否仅由空白字符(如空格、制表符、换行符)组成。
istitle()检查字符串是否所有单词大写字符开头。
isidentifier()检查字符串是否是有效标识符。
isprintable()检查字符串中是否所有字符都是可打印的。\n 不可打印
isdecimal()检查字符串是否是数字。
isdigit()检查字符串是否是数字。
isnumeric()检查字符串是否是数字。
isalnum()isdecimal()/isalpha()/isdigit()/isnumeric() 任意一个为True则返回True
# startswith(prefix[, start[, end]]) 检查字符串是否以 prefix 开头。
s = "hello world"  
print(s.startswith("hello"))  # 输出: True  
print(s.startswith("world"))  # 输出: False

# endswith(suffix[, start[, end]]) 检查字符串是否以 suffix 结束。
s = "hello world"  
print(s.endswith("world"))  # 输出: True  
print(s.endswith("hello"))  # 输出: False

# isalpha() 检查字符串是否仅由字母组成。
s = "hello"  
print(s.isalpha())  # 输出: True  
s = "hello123"  
print(s.isalpha())  # 输出: False

# isdigit() 检查字符串是否仅由数字组成。
s = "123"  
print(s.isdigit())  # 输出: True  
s = "12.3"  
print(s.isdigit())  # 输出: False

# islower() 检查字符串是否所有字母均为小写。
s = "hello"  
print(s.islower())  # 输出: True  
s = "Hello"  
print(s.islower())  # 输出: False

# isupper() 检查字符串是否所有字母均为大写。
s = "HELLO"  
print(s.isupper())  # 输出: True  
s = "Hello"  
print(s.isupper())  # 输出: False

# isspace() 检查字符串是否仅由空白字符(如空格、制表符、换行符)组成。
s = "   "  
print(s.isspace())  # 输出: True  
s = "   a"  
print(s.isspace())  # 输出: False

# istitle() 检查字符串是否所有单词大写字符开头。
s = "I Love Python"  
print(s.istitle())  # 输出: True  
s = "I love python"  
print(s.istitle())  # 输出: False

# isidentifier() 检查字符串是否是有效标识符。 
s = "I_Love_Python"  
print(s.isidentifier())  # 输出: True  
s = "I love python"  
print(s.isidentifier())  # 输出: False

# isprintable() 检查字符串中是否所有字符都是可打印的。\n 不可打印
s = "I Love Python"  
print(s.isprintable())  # 输出: True  
s = "I Love Python\n"  
print(s.isprintable())  # 输出: False

# isdecimal() 检查字符串是否是数字。
# isdigit() 检查字符串是否是数字。
# isnumeric() 检查字符串是否是数字。
s = "12345"  
print(s.isdecimal())  # 输出: True 
print(s.isdigit())  # 输出: True 
print(s.isnumeric())  # 输出: True 
s = "2²"  
print(s.isdecimal())  # 输出: False
print(s.isdigit())  # 输出: True 
print(s.isnumeric())  # 输出: True 
s = "ⅠⅡⅢⅣⅤ"  
print(s.isdecimal())  # 输出: False
print(s.isdigit())  # 输出: False
print(s.isnumeric())  # 输出: True 
s = "一二三四"  
print(s.isdecimal())  # 输出: False
print(s.isdigit())  # 输出: False
print(s.isnumeric())  # 输出: True 
字符串处理-格式化
  1. %运算符格式化
    使用%运算符进行字符串格式化,这是较早的一种方法,简单易用。
  • 优点: 简单,适用于简单的格式化场景。
  • 缺点: 对于复杂的格式化需求,不够灵活。
name = "Alice"  
age = 30  

# 基本语法  
greeting = "My name is %s, I am %d years old." % (name, age)  
print(greeting)  # 输出: My name is Alice, I am 30 years old.  

# 格式化数字  
pi = 3.1415926535  
formatted_pi = "Pi is approximately %.2f" % pi  
print(formatted_pi)  # 输出: Pi is approximately 3.14  

# 对齐文本  
text = "hello"  
# 右对齐,占10个字符位置  
right_aligned = "%10s" % text  
print(right_aligned)  # 输出:      hello  

# 左对齐  
left_aligned = "%-10s" % text  
print(left_aligned)  # 输出: hello     

# 居中对齐  
centered = "%*s" % (10, text)  # 需要计算总长度和填充字符  
# 更简单的方式  
centered = text.center(10)  
print(centered)       # 输出:   hello  

# 格式化日期和时间  
import time  
now = time.strftime("%Y-%m-%d %H:%M:%S")  
print(now)  # 输出当前日期和时间,例如: 2023-08-27 16:20:00
  1. str.format()方法
    format(*args, **kwargs) 格式化字符串,通过 {} 占位符替换内容。提供了更灵活和强大的字符串格式化功能,适用于复杂的格式化需求。
  • 优点: 灵活性强,支持索引和关键字参数,适合复杂的格式化需求。
  • 缺点: 语法较为冗长,不如f-strings简洁。
填充的数据取值范围说明
format_spec[[fill]align][sign][#][0][width][grouping_option][precision][type]格式化参数
fill<any character>任意字符(可选),用于填充空白区域。
align“<” | “>” | “=” | “^”对齐方式(可选),取值说明:
<: 左对齐(默认)。
>: 右对齐。
^: 居中对齐。
=: 与符号(如+或-)对齐,适用于数字。
sign“+” | “-” | " "指定数字的符号显示方式。取值说明:
+: 正数显示+,负数显示-。
-: 正数不显示符号,负数显示-。
(空格): 正数不显示符号,负数显示-。
##基底前缀-添加数值的基底前缀(如二进制0b、八进制0o、十六进制0x)。无具体值,只需添加#。
00前导零-在数字前添加前导零填充。无具体值,只需在 width 前加0。
widthdigit+指定输出的总宽度(包括符号、前缀、数字、小数点和小数部分等)。取值为正整数。
grouping_option“_” | “,”数字分组-为数字添加千位分隔符(如逗号,)。
precisiondigit+精度-指定小数点后的位数,或字符串的最大长度。取值说明:
整数:指定小数点后的位数。
None: 表示无限制。
type“b” | “c” | “d” | “e” | “E” | “f” | “F” | “g” | “G” | “n” | “o” | “s” | “x” | “X” | “%”格式类型-指定数值的显示格式。取值说明:
b: 二进制整数。
c: Unicode字符。
d: 十进制整数。
e: 科学计数法(小写)。
E: 科学计数法(大写)。
f: 固定小数点。
F: 固定小数点(大写)。
g: 自动选择f或e。
G: 自动选择f或e(大写)。
o: 八进制整数。
x: 十六进制整数(小写)。
X: 十六进制整数(大写)。
%: 百分比格式。
# 基本使用  
name = "Bob"  
age = 25  
greeting = "My name is {}, I am {} years old.".format(name, age)  
print(greeting)  # 输出: My name is Bob, I am 25 years old.  

# 索引引导  
nums = [10, 20, 30]  
print("Numbers: {0}, {1}, {2}".format(*nums))  
# 输出: Numbers: 10, 20, 30  

# 关键字参数  
person = {"name": "Charlie", "age": 35}  
greeting = "My name is {name}, I am {age} years old.".format(**person)  
print(greeting)  # 输出: My name is Charlie, I am 35 years old.  

# 格式化数字  
number = 1234.56789  
formatted_number = "Number: {0:.2f}".format(number)  
print(formatted_number)  # 输出: Number: 1234.57  

# 对齐文本  
text = "world"  
# 右对齐,占10个字符位置  
right_aligned = "{:>10}".format(text)  
print(right_aligned)  # 输出:      world  

# 左对齐  
left_aligned = "{:<10}".format(text)  
print(left_aligned)  # 输出: world    

# 居中对齐  
centered = "{:^10}".format(text)  
print(centered)       # 输出:   world  

# 填充字符  
filled = "{:*<10}".format("test")  
print(filled)       # 输出: test****  

# 动态格式化  
format_spec = ".2f"  
value = 3.1415926535  
print("Value: {:{}}".format(value, format_spec))  
# 输出: Value: 3.14  

# 混合使用索引和关键字  
data = ['blue', 'yellow', 'green']  
print("Colors: {0}, {1[1]}, {2}".format(data, data, data))  
# 输出: Colors: blue, yellow, green  

# 格式化日期和时间  
from datetime import datetime  
now = datetime.now()  
formatted_date = "Current date and time: {:%Y-%m-%d %H:%M:%S}".format(now)  
print(formatted_date)  
# 输出: Current date and time: 2023-08-27 16:25:30  

# 复杂的格式化示例  
#格式化一个表格  
fruits = [  
    ("Apple", 5, 1.50),  
    ("Banana", 7, 0.50),  
    ("Cherry", 10, 2.00)  
]  
print("{:<10}{:<7}{:<10}".format("Fruit", "Quantity", "Price"))  
print("-" * 27)  
for fruit, quantity, price in fruits:  
    print("{:<10}{:<7}{:<10.2f}".format(fruit, quantity, price))  
# 输出:  
# Fruit     Quantity   Price  
# ---------------------------  
# Apple       5       1.50  
# Banana      7       0.50  
# Cherry     10      2.00
  1. f-strings(格式化字符串字面量)
    从Python 3.6开始引入,提供了一种更简洁和高效的字符串格式化方式,直接在字符串中嵌入表达式。
  • 优点: 语法简洁,高效,支持直接嵌入表达式,提升可读性。
  • 缺点: 仅适用于Python 3.6及更高版本。
# 基本使用  
name = "Alice"  
age = 30  
greeting = f"My name is {name}, I am {age} years old."  
print(greeting)  # 输出: My name is Alice, I am 30 years old.  

# 数字格式化  
number = 1234.56789  
formatted_number = f"Number: {number:.2f}"  
print(formatted_number)  # 输出: Number: 1234.57  

# 对齐文本  
text = "hello"  
right_aligned = f"{text:>10}"  # 右对齐,占10个字符  
print(right_aligned)  # 输出:      hello  

left_aligned = f"{text:<10}"   # 左对齐  
print(left_aligned)  # 输出: hello    

centered = f"{text:^10}"       # 居中对齐  
print(centered)       # 输出:   hello  

# 填充字符  
filled = f"{'test':*<10}"  # 左对齐,填充*  
print(filled)       # 输出: test****  

# 表达式和计算  
a = 5  
b = 3  
sum_ab = f"The sum of {a} and {b} is {a + b}."  
print(sum_ab)  # 输出: The sum of 5 and 3 is 8.  

# 条件判断  
is_admin = True  
status = f"User is {'admin' if is_admin else 'standard'}."  
print(status)  # 输出: User is admin.  

# 循环生成内容  
fruits = ["apple", "banana", "cherry"]  
list_string = f"Fruits: {', '.join(fruits)}"  
print(list_string)  # 输出: Fruits: apple, banana, cherry  

# 格式化日期和时间  
from datetime import datetime  
now = datetime.now()  
formatted_date = f"Current date and time: {now:%Y-%m-%d %H:%M:%S}"  
print(formatted_date)  
# 输出: Current date and time: 2023-08-27 16:25:30  

# 动态格式化  
format_spec = ".2f"  
value = 3.1415926535  
formatted_value = f"Value: {value:{format_spec}}"  
print(formatted_value)  # 输出: Value: 3.14  

# 混合使用多种格式  
# 格式化一个表格  
fruits = [  
    ("Apple", 5, 1.50),  
    ("Banana", 7, 0.50),  
    ("Cherry", 10, 2.00)  
]  
print(f"{ '<10' :^27}")  
print(f"{'Fruit':<10}{'Quantity':<7}{'Price':<10}")  
print("-" * 27)  
for fruit, quantity, price in fruits:  
    print(f"{fruit:<10}{quantity:<7}{price:<10.2f}")  
# 输出:  
#             Fruit     Quantity   Price  
# ---------------------------  
# Apple       5       1.50  
# Banana      7       0.50  
# Cherry     10      2.00
  1. 自定义格式化
    通过定义类的__format__方法,实现自定义对象的格式化输出。
  • 优点: 提供灵活的自定义格式化选项,适用于复杂的对象格式化需求。
  • 缺点: 需要编写自定义类和方法,增加了代码复杂度。
class Person:  
    def __init__(self, name, age):  
        self.name = name  
        self.age = age  

    def __format__(self, format_spec):  
        if format_spec == 'long':  
            return f"Name: {self.name}, Age: {self.age}"  
        else:  
            return f"{self.name} ({self.age} years old)"  

# 使用自定义格式化  
person = Person("Bob", 30)  
print(f"Person info (long format): {person:'long'}")  
# 输出: Person info (long format): Name: Bob, Age: 30  

print(f"Person info (short format): {person}")  
# 输出: Person info (short format): Bob (30 years old)
字符串处理-编解码
函数说明
encode(encoding=‘utf-8’, errors=‘strict’)将字符串编码为 bytes 类型。
decode(encoding=‘utf-8’, errors=‘strict’)将 bytes 类型解码为字符串。
# encode(encoding='utf-8', errors='strict') 将字符串编码为 bytes 类型。
s = "hello"  
print(s.encode())  # 输出: b'hello'

# decode(encoding='utf-8', errors='strict') 将 bytes 类型解码为字符串。
b = b"hello"  
print(b.decode())  # 输出: hello
列表

在Python中,list(列表)是一种有序的、可更改的、允许重复元素的集合。它用于存储多个元素,这些元素可以是任意的数据类型(包括字符串、整数、浮点数和其他列表)。

列表处理-查询
# 获取元素
l = [1,2,3,4,5]
l # 输出: [1, 2, 3, 4, 5]
l[0] # 输出: 1
l[len(l)-1] # 输出: 5
l[-1] # 输出: 5

# 查找数量
list1 = ["python", "c++", "java", "php", "java"]
print(list1.count("java")) # 输出: 2

# 查找索引
list1 = ["python", "c++", "java", "php", "java"]
print(list1.index("java")) # 输出: 2
print(list1.index("java",3,5)) # 输出: 4
列表处理-修改
# 增加
list1 = [1, 2]  
list1.append(3)  # 在列表末尾添加执行元素
print(list1)  # 输出:[1, 2, 3]
list1.extend([3, 4])  # 在列表末尾添加可迭代对象
print(list1)  # 输出:[1, 2, 3, 3, 4]
list1.insert(0, 1)  # 在索引0处插入1  
print(list1)  # 输出:[1, 1, 2, 3, 3, 4]
list1[-1:] = [1,2,3] # 通过切片的方式追加元素,会修改最后一个元素
print(list1)  # 输出:[1, 1, 2, 3, 3, 1, 2, 3]
list1[len(list1):] = [1,2,3] # 通过切片的方式追加元素,不会修改最后一个元素
print(list1)  # 输出:[1, 1, 2, 3, 3, 1, 2, 3, 1, 2, 3]

# 删除,还可以通过 del 关键字删除
list2=["python", "c++", "java", "php"]
list2.remove("java")
print(list2) # 输出:['python', 'c++', 'php']
list2.pop(1)
print(list2) # 输出:['python', 'php']
list2.clear()
print(list2) # 输出:[]

# 修改
list3=["python", "c++", "java", "php"]
list3[1]="js"
print(list3) # 输出:['python', 'js', 'java', 'php']
list3[3:] = ["c++", "c", "123"]
print(list3) # 输出:['python', 'js', 'java', 'c++', 'c', '123']
列表处理-排序
# 排序可以用BIF中的sorted/reversed函数,也可以用列表自带的sort/reverse函数,BIF函数输出新列表,自带的函数直接修改列表。
list4=[1,2,0,4,2,1,5]
list4.sort()
print(list4) # 输出: [0, 1, 1, 2, 2, 4, 5]
list4=[1,2,0,4,2,1,5]
list4.sort(reverse=True)
print(list4) # 输出: [5, 4, 2, 2, 1, 1, 0]
list4.reverse()
print(list4) # 输出: [0, 1, 1, 2, 2, 4, 5]
列表处理-加法与乘法运算
print([1,2,3]+[2,3,4]) # 输出:[1, 2, 3, 2, 3, 4]
print([1,2,3]*3) # 输出:[1, 2, 3, 1, 2, 3, 1, 2, 3]
列表处理-嵌套
matrix=[[0,1,2],
        [1,2,3],
        [3,4,5]]
for i in matrix:
    for each in i:
        print(each, end=' ')
    print()
# 输出:
0 1 2 
1 2 3 
3 4 5

# 可以 for 循环创建,较简单不做示例
# 创建嵌套列表,拷贝引用,注意内存问题
A = [[1] * 3] * 3
print(A) # 输出: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
A[1][1] = 2
print(A) # 输出: [[1, 2, 1], [1, 2, 1], [1, 2, 1]]

# 还可以通过列表推导式创建,在下一小节进行说明
列表处理-列表推导式
# 筛选
codes = ["python", "java", "c++", "php", "js"]
new_codes = [code for code in codes if len(code) == 3 ]
print(new_codes) # 输出: ['c++', 'php']

# 创建嵌套列表
A = [[1]*3 for i in range(3)]
print(A) # 输出: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
A[1][1] = 2
print(A) # 输出: [[1, 1, 1], [1, 2, 1], [1, 1, 1]]

# 嵌套语法
A = [s*d for s in "hello" if s != 'o' for d in range(1,4) if d != 2]
print(A) # 输出: ['h', 'hhh', 'e', 'eee', 'l', 'lll', 'l', 'lll']
元组

在Python中,tuple(元组)是一种有序的、不可更改的集合,用于存储多个元素。这些元素可以是任意的数据类型(包括字符串、整数、浮点数和其他元组)。与list不同,tuple一旦创建,其元素不可修改。

元组处理-查询
# 通过小括号创建元组,实际上可以省略小括号,但不建议省略
# 生成一个元素的元组
x = (250)
print(type(x)) # 输出: <class 'int'>
x = (250,)
print(type(x)) # 输出: <class 'tuple'>

# 获取元素
t = (1,2,3,4,5)
print(t) # 输出: [1, 2, 3, 4, 5]
print(t[0]) # 输出: 1
print(t[len(t)-1]) # 输出: 5
print(t[-1]) # 输出: 5

# 查找数量
t = ("python", "c++", "java", "php", "java")
print(t.count("java")) # 输出: 2

# 查找索引
t = ("python", "c++", "java", "php", "java")
print(t.index("java")) # 输出: 2
print(t.index("java",3,5)) # 输出: 4

# 不可修改
t[2] = 1 # 报错:
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\test.py", line 17, in <module>
    t[2] = 1
TypeError: 'tuple' object does not support item assignment
元组处理-加法与乘法运算

与列表的拼接、复制用法相同

元组处理-嵌套

嵌套用法与列表相同,两个元组可以直接用,进行嵌套

A = (1,2,3)
B = (2,3,4)
C = A,B
print(C) # 输出: ((1, 2, 3), (2, 3, 4))
元组处理-列表推导式

元组也可以作用于列表推导式中,用于生成列表。不存在元组推导式。()的的写法输出的是生成器。

A = (1,2,3,4,5)
B = [each * 2 for each in A if each > 2]
print(B) # 输出: [6, 8, 10]

# 不存在元组推导式
(i*2 for i in range(3))
<generator object <genexpr> at 0x000001CFEC651190>
字典

在Python中,dict(字典)是一种存储数据的集合类型,它以 键值对(key-value) 的形式来存储数据。字典是可变的、无序的(在Python 3.7之前没有顺序,3.7及以后版本保留插入顺序),并且键是唯一的。
字典的嵌套与迭代方式跟列表是一样的,不做赘述。

字典的创建
# 定义一个空字典  
empty_dict = {}  

# 定义一个包含多个键值对的字典  
person = {  
    "name": "Alice",  
    "age": 30,  
    "city": "Beijing"  
}
print(type(person)) # 输出: <class 'dict'>
print(person) # 输出: {'name': 'Alice', 'age': 30, 'city': 'Beijing'}
print(person["name"]) # 输出: Alice
person["name"] = "Hello"
person["level"] = "S"
print(person) # 输出: {'name': 'Hello', 'age': 30, 'city': 'Beijing', 'level': 'S'}
person2 = dict(name="Alice", age=30, city="Beijing")
print(person2) # 输出: {'name': 'Alice', 'age': 30, 'city': 'Beijing'}
person3 = dict([("name", "Alice"), ("age", 30), ("city", "Beijing")])
print(person3) # 输出: {'name': 'Alice', 'age': 30, 'city': 'Beijing'}
person4 = dict({"name":"Alice", "age":30, "city":"Beijing"})
print(person4) # 输出: {'name': 'Alice', 'age': 30, 'city': 'Beijing'}
person5 = dict({"name":"Alice", "age":30}, city="Beijing")
print(person5) # 输出: {'name': 'Alice', 'age': 30, 'city': 'Beijing'}
person6 = dict(zip(["name","age","city"], ["Alice", 30, "Beijing"]))
print(person6) # 输出: {'name': 'Alice', 'age': 30, 'city': 'Beijing'}

person7 = dict.fromkeys("python", 100)
print(person7) # 输出: {'p': 100, 'y': 100, 't': 100, 'h': 100, 'o': 100, 'n': 100}
person8 = dict.fromkeys([1,2,3],102)
print(person8) # 输出: {1: 102, 2: 102, 3: 102}
字典的查询
# []下标访问
person = {"name": "Alice","age": 30,"city": "Beijing"}
print(person["name"]) # 输出: Alice
print(person["no"]) # 报错:
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\test.py", line 3, in <module>
    print(person["no"])
KeyError: 'no'

# get方法
person = {"name": "Alice","age": 30,"city": "Beijing"}
print(person.get("name")) # 输出: Alice
print(person.get("no")) # 输出: None
print(person.get("no", "default")) # 输出: default

# 获取所有元素信息
person = {"name": "Alice","age": 30,"city": "Beijing"}
keys = person.keys()
values = person.values()
items = person.items()
print(keys) # 输出: dict_keys(['name', 'age', 'city'])
print(values) # 输出: dict_values(['Alice', 30, 'Beijing'])
print(items) # 输出: dict_items([('name', 'Alice'), ('age', 30), ('city', 'Beijing')])
字典的删除与修改
person = {"name": "Alice","age": 30,"city": "Beijing"}
person.pop("name")
print(person) # 输出: {'age': 30, 'city': 'Beijing'}
person.popitem() # Python3.7及其之后版本有序,popitem从后插入的数据开始弹出数据
print(person) # 输出: {'age': 30}
person.pop("no") # 报错: 
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\test.py", line 6, in <module>
    person.pop("no")
KeyError: 'no'
# del 关键字也可以删除,不再赘述

# 清空字典
person = {"name": "Alice","age": 30,"city": "Beijing"}
person.clear()
print(person) # 输出: {}

# 更新元素
# 可以直接通过[key]=value的方式修改
# setdefault 方法,如果不存在则通过默认值添加一个元素,如果存在则不修改元素
person = {"name": "Alice","age": 30,"city": "Beijing"}
print(person.setdefault("age",50)) # 输出: 30
print(person.setdefault("no",100)) # 输出: 100
print(person) # 输出: {'name': 'Alice', 'age': 30, 'city': 'Beijing', 'no': 100}

字典推导式
d = {x:x+100 for x in range(3)}
print(d) # 输出: {0: 100, 1: 101, 2: 102}
d2 = {v:k for k,v in d.items()}
print(d2) # 输出: {100: 0, 101: 1, 102: 2}
集合

在Python中,集合(set)是一个无序的、不可重复的数据结构,用于存储唯一的元素。与列表不同,集合不保持元素的顺序,并且不允许有重复的元素。集合非常适合用于需要快速查找、去重以及进行集合运算的场景。

  • set 可变集合
  • frozenset 不可变集合
集合创建
A = { s for s in "python"}
print(A) # 输出: {'o', 'n', 't', 'p', 'h', 'y'}
B = {"python", "c++"}
print(B) # 输出: {'c++', 'python'}
C = set("python")
print(C) # 输出: {'o', 'n', 't', 'p', 'h', 'y'}
D = set([1,1,1,2,2,2,3,3,3])
print(D) # 输出: {1, 2, 3}

# 不可变集合
A = frozenset("Python")
print(A) # 输出: frozenset({'P', 'o', 'y', 'h', 't', 'n'})
集合查询
# 迭代查询
A = { s for s in "python"}
for each in A:
    print(each)
# 输出:
p
h
o
y
t
n

# 判断是否有交集
A = { s for s in "python"}
print(A.isdisjoint("c++")) # 输出: True
print(A.isdisjoint("json")) # 输出: False
集合运算
# 判断是否是某个集合的子集
A = { s for s in "python"}
print(A.issubset("thon")) # 输出: False
print(A.issubset("python")) # 输出: True
print(A.issubset("www.python.com")) # 输出: True
print(A < set("thon")) # 输出: False
print(A < set("python")) # 输出: False
print(A <= set("python")) # 输出: True
print(A < set("www.python.com")) # 输出: True
print(A < "thon") # 报错:
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\test.py", line 6, in <module>
    print(A < "thon")
TypeError: '<' not supported between instances of 'set' and 'str'

# 判断是否是某个集合的超集
A = { s for s in "python"}
print(A.issuperset("thon")) # 输出: True
print(A.issuperset("python")) # 输出: True
print(A.issuperset("www.python.com")) # 输出: False
print(A > set("thon")) # 输出: True
print(A > set("python")) # 输出: False
print(A >= set("python")) # 输出: True
print(A > set("www.python.com")) # 输出: False
print(A > "thon") # 报错:
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\test.py", line 6, in <module>
    print(A > "thon")
TypeError: '>' not supported between instances of 'set' and 'str'

# 计算并集
A = { s for s in "python"}
print(A.union("json",{1,2,3})) # 输出: {1, 2, 3, 's', 'j', 'p', 'y', 'o', 'n', 'h', 't'}
print(A | set("json") | {1,2,3}) # 输出: {1, 2, 3, 's', 'j', 'p', 'y', 'o', 'n', 'h', 't'}

# 计算交集
A = { s for s in "python"}
print(A.intersection("json","thon")) # 输出: {'o', 'n'}
print(A & set("json") & set("thon")) # 输出: {'o', 'n'}

# 计算差集
A = { s for s in "python"}
print(A.difference("json","thon")) # 输出: {'p', 'y'}
print(A - set("json") - set("thon")) # 输出: {'p', 'y'}

# 计算对称差集(两个集合并集-交集的结果。不可多参数)
A = { s for s in "python"}
print(A.symmetric_difference("hello")) # 输出: {'n', 't', 'p', 'y', 'e', 'l'}
print(A ^ set("hello")) # 输出: {'n', 't', 'p', 'y', 'e', 'l'}
集合修改

frozenset不可修改,这里只展示set的修改

# frozenset 无法更新元素
A = frozenset("Python")
A.update([1,1], "1,2") # 报错:frozenset 无法被修改
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\test.py", line 4, in <module>
    A.update([1,1], "1,2")
AttributeError: 'frozenset' object has no attribute 'update'

# set 更新元素
A = set("python")
A.update([1,1],"12") # 插入可迭代对象
print(A) # 输出: {1, 'h', 'o', '2', 'n', 't', 'p', 'y', '1'}
A = set("python")
A.intersection_update("hello") # 更新为并集
print(A) # 输出: {'h', 'o'}
A = set("python")
A.difference_update("json","hello") # 更新为差集
print(A) # 输出: {'t', 'p', 'y'}
A = set("python")
A.symmetric_difference_update("json") # 更新为对称差集
print(A) # 输出: {'h', 't', 's', 'j', 'p', 'y'}

# set 元素增删
A = set("python")
A.add("hello") # 插入一个元素
print(A) # 输出: {'n', 'y', 'hello', 'h', 't', 'p', 'o'}
A.remove("hello") # 删除一个元素
print(A) # 输出: {'n', 'y', 'h', 't', 'p', 'o'}
A.add("hello")
A.discard("hello") # 静默删除
print(A) # 输出: {'n', 'y', 'h', 't', 'p', 'o'}
A.pop() # 随机弹出一个元素
print(A) # 输出: {'y', 'h', 't', 'p', 'o'}
A.discard("no") # 删除一个不存在的元素
print(A) # 输出: {'y', 'h', 't', 'p', 'o'}
A.remove("no") # 删除一个不存在的元素,抛出异常
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\test.py", line 14, in <module>
    A.remove("no") # 删除一个不存在的元素
KeyError: 'no'

# 清空集合
A = set("python")
A.clear()
print(A) # 输出: set()
集合推导式
A = { s for s in "python"}
print(A) # 输出: {'n', 'o', 'p', 't', 'y', 'h'}
集合嵌套

集合中的元素必须是可hash的(不可修改的数据类型)。所以无法直接创建嵌套的集合。需要用到frozenset作为元素值才可以。

 A = {"hello", 1, 2, [3, 4]} # list 不是可hash的,不能作为元素
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    A = {"hello", 1, 2, [3, 4]}
TypeError: unhashable type: 'list'
A = {"hello", 1, 2, {3, 4}} # set不是可hash的,不能作为元素
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    A = {"hello", 1, 2, {3, 4}}
TypeError: unhashable type: 'set'

# 通过frozenset实现集合嵌套
A = {"hello", 1, 2, frozenset([1,2,3])}
print(A) # 输出: {frozenset({1, 2, 3}), 1, 2, 'hello'}

2. 运算符

Python提供了多种运算符,用于执行算术、比较、逻辑、赋值、位运算等操作。

算术运算符

用于执行基本的数学运算。

运算符描述示例
+加法5 + 3 → 8
-减法5 - 3 → 2
*乘法5 * 3 → 15
/除法10 / 3 → 3.333…
//整除10 // 3 → 3
%取模10 % 3 → 1
**幂运算2 ** 3 → 8

比较运算符

用于比较两个值的大小关系。

运算符描述示例
==等于5 == 5 → True
!=不等于5 != 3 → True
>大于5 > 3 → True
<小于3 < 5 → True
>=大于等于5 >= 5 → True
is判断 ida = “a” b = a a is b → True
is not判断 ida = “a” b = a a is not b → False

逻辑运算符

用于组合条件语句,实现更复杂的逻辑判断。

运算符描述示例
andTrue and True → True
orTrue or False → True
notnot False → True

赋值运算符

用于简化赋值操作,结合算术运算符。

运算符描述示例
=赋值x = 5
+=加法赋值x += 3 → x = x + 3
-=减法赋值x -= 2 → x = x - 2
*=乘法赋值x *= 4 → x = x * 4
/=除法赋值x /= 2 → x = x / 2

位运算符

用于处理二进制数据,在底层编程中常用。

运算符描述示例
&按位与5 & 3 → 1
|按位或5 | 3 → 7
^按位异或5 ^ 3 → 6
~按位取反~5 → -6
<<左移5 << 1 → 10
>>右移10 >> 1 → 5

优先级

运算符的执行顺序遵循优先级规则,以下是主要运算符的优先级(从高到低):

  1. 幂运算 (**)
  2. 按位取反 (~)
  3. 乘法 (*), 除法 (/), 整除 (//), 取模 (%)
  4. 加法 (+), 减法 (-)
  5. 按位移(<<, >>)
  6. 按位与 (&)
  7. 按位异或 (^)
  8. 按位或 (|)
  9. 比较运算符 (<, >, ==, etc.)
  10. 逻辑非 (`not)
  11. 逻辑与 (and)
  12. 逻辑或 (or)
  13. 宽度优先运算符(in, is, etc.)
  14. 赋值运算符(=, +=, etc.)
    在表达式中,如果有多个运算符,可以通过括号 () 改变执行顺序。

3. 控制流

控制流语句用于改变程序的执行顺序,主要包括条件判断和循环结构。

条件判断 (if语句)

用于根据条件执行不同的代码块。写法与 c++ 无异。三元运算可以写成条件表达式。写法为:条件成立执行的语句 if condition else 条件不成立执行的语句。比如: print(“及格”) if score >= 60 else print(“不及格”)

# 1. 单个 if 语句,用于在条件满足时执行一段代码。
a = 5  
if a > 10:  
    print("a 大于 10")
# 输出:无输出,因为条件不满足  

# 2. if-else 语句,用于在条件满足时执行一段代码,不满足时执行另一段代码。
a = 5  
if a > 10:  
    print("a 大于 10")  
else:  
    print("a 小于或等于 10")
# 输出:a 小于或等于 10  

# 3. if-elif-else 语句,用于处理多个条件判断,依次检查每个条件。
a = 5  
if a > 10:  
    print("a 大于 10")  
elif a == 5:  
    print("a 等于 5")  
else:  
    print("a 小于 5")
# 输出:a 等于 5  

# 4. 嵌套的 if 语句,在 if 或 else 块内部嵌套另一个 if 语句。
a = 5  
b = 3  
if a > 4:  
    if b > 2:  
        print("a > 4 且 b > 2")  
    else:  
        print("a > 4 但 b <= 2")  
else:  
    print("a <= 4")
# 输出:a > 4 且 b > 2  

# 5. 一行 if-else(三元运算符),将 if-else 写成一行,适用于简单的条件判断。
a = 5  
result = "a 大于 10" if a > 10 else "a 小于或等于 10"  
print(result)
# 输出:a 小于或等于 10  

# 6. if 在列表推导式中的使用,在列表推导式中使用 if 过滤元素。
numbers = [1, 2, 3, 4, 5]  
even_numbers = [num for num in numbers if num % 2 == 0]  
print(even_numbers)
# 输出:[2, 4]  

# 7. if 在生成器表达式中的使用,在生成器表达式中使用 if 过滤元素。
numbers = [1, 2, 3, 4, 5]  
even_numbers = (num for num in numbers if num % 2 == 0)  
print(list(even_numbers))
# 输出:[2, 4]  

循环结构

循环用于重复执行一段代码,直到满足退出条件。Python主要有 for 和 while 两种循环。

while 循环写法

根据条件反复执行一段代码,直到条件不成立。Python 有 while else 写法,可以用于确认循环的退出状态,是否完全执行完循环。比如:

# 1. 基础 while 循环,根据条件重复执行代码块,直到条件为 False。
# 示例:从 1 累加到 5
count = 1
total = 0
while count <= 5:
    total += count
    count += 1
print(total)  # 输出 15

# 2. 带 else 子句的 while 循环,当循环正常结束(未被 break 中断)时执行 else 块。
# 示例:循环结束后打印提示
num = 3
while num > 0:
    print(num)
    num -= 1
else:
    print("循环正常结束!")
# 输出:
# 3
# 2
# 1
# 循环正常结束!

# 3. 使用 break 强制退出循环,通过 break 提前终止循环。
# 示例:找到第一个大于 10 的数
nums = [5, 8, 12, 3, 15]
index = 0
while index < len(nums):
    if nums[index] > 10:
        print(f"找到 {nums[index]}")
        break
    index += 1
# 输出:找到 12

# 4. 使用 continue 跳过当前迭代,跳过当前循环的剩余代码,直接进入下一轮循环。
# 示例:打印 1 到 5 中的奇数
num = 0
while num < 5:
    num += 1
    if num % 2 == 0:
        continue
    print(num)
# 输出:
# 1
# 3
# 5

# 5. 无限循环,使用 while True 创建无限循环,依赖内部条件退出。
# 示例:用户输入验证
while True:
    user_input = input("请输入 'exit' 退出:")
    if user_input.lower() == "exit":
        print("程序已退出!")
        break

# 6. 结合标志变量控制循环,通过布尔变量(如 running)动态控制循环的执行。
# 示例:根据标志变量退出循环
running = True
while running:
    command = input("输入命令(stop 结束):")
    if command == "stop":
        running = False
    else:
        print(f"执行命令:{command}")

# 7. 循环与输入验证,确保用户输入符合要求。
# 示例:强制输入数字
while True:
    user_input = input("请输入一个数字:")
    if user_input.isdigit():
        num = int(user_input)
        print(f"输入的数字是:{num}")
        break
    else:
        print("输入无效,请重试!")

# 8. 处理动态修改的集合,循环中动态增删列表元素(需谨慎操作)。
# 示例:删除列表中的偶数
numbers = [1, 2, 3, 4, 5, 6]
i = 0
while i < len(numbers):
    if numbers[i] % 2 == 0:
        del numbers[i]
    else:
        i += 1
print(numbers)  # 输出 [1, 3, 5]

# 9. 结合函数调用,在循环条件中调用函数动态判断。
# 示例:根据函数返回值控制循环
def should_continue(value):
    return value < 10

value = 5
while should_continue(value):
    print(value)
    value += 1
# 输出 5, 6, 7, 8, 9

# 10. 结合异常处理,捕获循环中可能的错误。
# 示例:处理除零错误
a, b = 5, 0
while True:
    try:
        result = a / b
        print(result)
        break
    except ZeroDivisionError:
        print("除数不能为 0,请修改 b 的值!")
        b = int(input("输入新的 b 值:"))
# 11. 循环与生成器/迭代器,结合生成器逐步生成数据。
# 示例:生成器生成斐波那契数列
def fibonacci_gen(max_num):
    a, b = 0, 1
    while a < max_num:
        yield a
        a, b = b, a + b

# 使用生成器迭代
for num in fibonacci_gen(20):
    print(num, end=" ")  # 输出 0 1 1 2 3 5 8 13

# 12. 多条件组合,通过逻辑运算符组合多个条件。
# 示例:同时满足两个条件
x = 0
y = 5
while x < 3 and y > 0:
    print(x, y)
    x += 1
    y -= 1
# 输出:
# 0 5
# 1 4
# 2 3
for 循环写法

用于遍历序列(如列表、元组、字符串等)或其他可迭代对象。for 循环也支持 else 的写法,作用与 while else 相同。for 循环的写法包括以下:

# 1. 遍历可迭代对象,直接遍历列表、元组、字符串等可迭代对象。
# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# 遍历元组
colors = ("red", "green", "blue")
for color in colors:
    print(color)

# 遍历字符串
for char in "Python":
    print(char)

# 2. 结合 range() 按索引遍历,使用 range() 生成索引序列。
# 遍历数字序列
for i in range(5):  # 0到4
    print(i)

# 遍历列表的索引
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
    print(fruits[i])

# 3. 使用 enumerate() 获取索引和值,同时获取元素及其索引
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")

# 4. 遍历字典,分别遍历字典的键、值或键值对
d = {"a": 1, "b": 2, "c": 3}
# 遍历键
for key in d:
    print(key)
# 遍历值
for value in d.values():
    print(value)
# 遍历键值对
for key, value in d.items():
    print(f"{key}: {value}")

# 5. 使用 zip() 并行遍历多个可迭代对象,同时遍历多个可迭代对象,按元素一一配对
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(f"{name} is {age} years old")


# 6. 嵌套循环
# 普通嵌套循环
for i in range(3):
    for j in range(2):
        print(f"({i}, {j})")

# 列表推导式中的嵌套
matrix = [[i * j for j in range(3)] for i in range(5)] # [[0, 0, 0], [0, 1, 2], [0, 2, 4], [0, 3, 6], [0, 4, 8]]

# 7. 列表推导式中的 for,简化循环生成列表的写法。
squares = [x ** 2 for x in range(5)]  # [0, 1, 4, 9, 16]

# 8. 生成器表达式中的 for,生成器惰性迭代数据,节省内存。
gen = (x ** 2 for x in range(5))
for num in gen:
    print(num)

# 9. 结合 else 子句,当循环正常结束(未被 break 中断)时执行 else 块。
for i in range(3):
    print(i)
else:
    print("Loop completed normally")

# 10. 遍历文件的行,逐行读取文件内容。
with open("data.txt") as file:
    for line in file:
        print(line.strip())  # 去除换行符

# 11. 解包变量,在循环中解包元组或列表。
points = [(1, 2), (3, 4), (5, 6)]
for x, y in points:
    print(f"x={x}, y={y}")

# 使用星号解包剩余元素
records = [("a", 1, 2), ("b", 3), ("c", 4, 5, 6)]
for tag, *nums in records:
    print(f"{tag}: {nums}")

# 12. 结合条件过滤,在循环中使用 if 过滤元素。
for num in range(10):
    if num % 2 == 0:
        print(num)
# 列表推导式中的条件过滤
evens = [num for num in range(10) if num % 2 == 0]

# 13. 使用 itertools 模块,结合标准库实现复杂迭代逻辑(需导入 itertools)。
import itertools

# 连接多个可迭代对象
for item in itertools.chain([1, 2], ["a", "b"]):
    print(item)  # 输出 1, 2, a, b

# 无限循环(需手动终止)
count = 0
for num in itertools.cycle([1, 2, 3]):
    print(num)
    count += 1
    if count > 5:
        break

# 14. 遍历自定义迭代器,实现 __iter__ 和 __next__ 方法创建自定义迭代器。
class Counter:
    def __init__(self, low, high):
        self.current = low
        self.high = high

    def __iter__(self):
        return self

    def __next__(self):
        if self.current > self.high:
            raise StopIteration
        else:
            self.current += 1
            return self.current - 1

for num in Counter(3, 5):
    print(num)  # 输出 3, 4, 5
循环控制语句
  • break:立即退出循环。
  • continue:跳过当前循环,继续下一次循环。
  • pass:作为占位符,表示“什么都不做”。
for i in range(1, 6):  
    if i == 3:  
        continue  
    print(i)  
# 输出:  
# 1  
# 2  
# 4  
# 5
递归替代循环

递归与循环结合,通过递归替代循环(但通常循环更高效)。

# 示例:递归实现累加(仅为演示,实际推荐循环)
def recursive_sum(n, total=0):
    if n == 0:
        return total
    return recursive_sum(n-1, total + n)

print(recursive_sum(5))  # 输出 15

4. 函数

函数是可重复使用的代码块,通过给函数命名,可以在程序的不同位置多次调用它。

函数定义

使用 def 关键字定义函数。

def greet(name):  
    """打印个性化的问候信息"""  
    print(f"Hello, {name}!")  

# 函数调用  
greet("Alice")  # 输出:Hello, Alice!

函数参数与返回值

函数可以接受参数,并返回计算后的值。Python支持返回多个值,实际是作为元组输出。

def add_numbers(a, b):  
    """返回两个数的和"""  
    return a + b  

result = add_numbers(5, 3) # 位置参数,通过实参与形参的位置来确认其对应关系  
print(result)  # 输出:8
result = add_numbers(b = 5, a = 3) # 关键字参数,通过实参给形参赋值的方式来确认其对应关系 
print(result)  # 输出:8
result = add_numbers(5, b= 3) # 混用方式,位置参数必须在关键字参数之前。  
print(result)  # 输出:8
result = add_numbers(a = 5, 3) # 位置参数必须在关键字参数前面,不然报语法错误: SyntaxError: invalid syntax
result = add_numbers(5, a = 3) # 位置参数与关键字参数都执行a形参,报错:
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\test.py", line 5, in <module>
    result = add_numbers(5, a = 3)
TypeError: add_numbers() got multiple values for argument 'a'

# 函数定义中,形参列表可通过 / 分割,/ 前面的参数必须通过位置参数传递。
def add_numbers(a, /, b):  
    """返回两个数的和"""  
    return a + b
print(add_numbers(5, 3))  # 输出:8
print(add_numbers(a = 5, b = 3)) # 报错:
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\test.py", line 5, in <module>
    print(add_numbers(a = 5, b = 3))
TypeError: add_numbers() got some positional-only arguments passed as keyword arguments: 'a'

# 函数定义中,形参列表可通过 * 分割,* 后面的参数必须通过关键字参数传递。
def add_numbers(a, *, b):  
    """返回两个数的和"""  
    return a + b
print(add_numbers(a = 5, b = 3))  # 输出:8
print(add_numbers(5, 3)) # 报错:
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\test.py", line 5, in <module>
    print(add_numbers(5, 3))
TypeError: add_numbers() takes 1 positional argument but 2 were given
默认参数值

可以为参数设置默认值,当调用函数时不提供该参数时,使用默认值。默认值参数必须在参数列表的最后。

def power(base, exponent=2):  
    return base ** exponent  

print(power(5))        # 输出:25(5²)  
print(power(5, 3))      # 输出:125(5³)
可变参数

允许函数接受任意数量的参数。

  • *args:将多个参数收集成一个元组。
  • **kwargs:将多个键值对参数收集成一个字典。
def my_function(*args):  
    for arg in args:  
        print(arg)  

my_function('a', 'b', 'c')  
# 输出:  
# a  
# b  
# c  

def my_function(**kwargs):  
    for key, value in kwargs.items():  
        print(f"{key}: {value}")  

my_function(name="Bob", age=30, city="New York")  
# 输出:  
# name: Bob  
# age: 30  
# city: New York  

def combined(a, b, *args, **kwargs):  
    print(f"a={a}, b={b}, args={args}, kwargs={kwargs}")  

combined(1, 2, 'x', 'y', z=3, w=4)  
# 输出:  
# a=1, b=2, args=('x', 'y'), kwargs={'z': 3, 'w': 4}
解包参数

将列表,元组等类型对象解包成多个参数传递给函数

def add_numbers(a, b):  
    """返回两个数的和"""  
    return a + b
args = [5, 3]
print(add_numbers(*args))  # 输出:8
kwargs = {'a':5, 'b':3}
print(add_numbers(**kwargs))  # 输出:8

函数的作用域

在函数内部定义的变量只在函数内部有效,这叫做函数的局部作用域。如果需要访问全局变量,可以使用 global 关键字声明。
作用域优先级规则LEGB。

优先级变量属性说明
1Local局部作用域
2Enclosed嵌套函数的外层函数作用域
3Global全局作用域
4Build-In内置作用域
x = 100  # 全局变量  

def my_func():  
    x = 200  # 局部变量  
    print("局部变量x:", x)  

my_func()  
print("全局变量x:", x)  
# 输出:  
# 局部变量x: 200  
# 全局变量x: 100  

def modify_global():  
    global x  
    x = 200  
    print("修改后的全局变量x:", x)  

modify_global()  
print("全局变量x被修改后:", x)  
# 输出:  
# 修改后的全局变量x: 200  
# 全局变量x被修改后: 200

# 函数嵌套时,优先使用函数内定义的变量
def fun_a():
    x = 100
    def fun_b():
        x = 200
        print("in fun b, x=", x)
    fun_b()
    print("in fun a, x=", x)

fun_a()
# 输出:
# in fun b, x= 200
# in fun a, x= 100

# 可以通过nonlocal 关键字修改作用域
def fun_a():
    x = 100
    def fun_b():
        nonlocal x
        x = 200
        print("in fun b, x=", x)
    fun_b()
    print("in fun a, x=", x)

fun_a()
# 输出:
# in fun b, x= 200
# in fun a, x= 200

函数注释与文档字符串

使用文档字符串(docstring)为函数添加注释,方便他人理解函数的功能和使用方法。

def square(number: int) -> int:   # number: int写法是类型注释,表示number希望接受一个int类型的参数,int数据的列表可以写成list[int],键为str值为int的字典可以写成dict[str,int]
    """计算一个整数的平方。  
    
    Args:  
        number (int): 需要计算平方的整数。  
    
    Returns:  
        int: 平方值。  
    """  
    return number ** 2  

print(square(4))  # 输出:16

# 函数内省参数
print(square.__name__) # 输出: square
print(square.__doc__)
# 输出: 
#计算一个整数的平方。  
#    
#    Args:  
#        number (int): 需要计算平方的整数。  
#    
#    Returns:  
#        int: 平方值。  
print(square.__annotations__) # 输出: {'number': <class 'int'>, 'return': <class 'int'>}

匿名函数(lambda)

使用 lambda 关键字可以定义简短的匿名函数。

sum = lambda x, y: x + y  
print(sum(5, 3))  # 输出:8  

numbers = [1, 2, 3, 4, 5]  
squared_numbers = list(map(lambda x: x ** 2, numbers))  
print(squared_numbers)  # 输出:[1, 4, 9, 16, 25]

函数的可调用性

函数本身是一个对象,可以作为参数传递给其他函数,或者赋值给变量。

def add(a, b):  
    return a + b  

def multiply(a, b):  
    return a * b  

functions = [add, multiply]  
print(functions[0](5,3))  # 输出:8  
print(functions[1](5,3))  # 输出:15

5. 模块与包

模块(module)是扩展Python功能的重要手段,它允许在多个程序中重复使用代码。Python的标准库中包含了大量内置模块,可以直接导入使用。此外,用户也可以根据需要创建自己的模块或包。

导入模块

使用 import 语句导入模块,可以一次性导入整个模块,也可以导入模块中的特定部分。

# 导入整个模块  
import math  
print(math.sqrt(9))  # 输出:3.0  

# 导入模块中的特定函数  
from math import sin, cos  
print(sin(math.pi/2))  # 输出:1.0  

# 给导入的模块或函数起别名  
import pandas as pd  
from numpy import sum as np_sum  

print(pd.__version__)  # 输出:pandas的版本  
print(np_sum([1, 2, 3]))  # 输出:6  

# 导入多个模块  
import sys, os, math

创建自定义模块

任何以 .py 为扩展名的文件都是一个Python模块。可以将函数、变量和类等定义在模块中,然后导入使用。

假设有一个文件 mymodule.py,内容如下:

# mymodule.py  
def hello(name):  
    print(f"Hello, {name}!")  

version = "1.0.0"  

numbers = [1, 2, 3, 4, 5]

然后可以在另一个文件中导入并使用它:

import mymodule  
mymodule.hello("Alice")  # 输出:Hello, Alice!  
print(mymodule.version)  # 输出:1.0.0  
print(mymodule.numbers)  # 输出:[1, 2, 3, 4, 5]

模块的 name 属性

每个模块都有一个 name 属性。通过检查 name 的值,可以实现“作为脚本运行时执行的代码”。

# mymodule.py  
def main():  
    print("This is the main function.")  

if __name__ == "__main__":  
    main()

当直接运行 mymodule.py 时,会执行 main() 函数;而当导入该模块时,main() 不会自动执行。

创建包

包是模块的集合,用于组织和管理大型项目。一个目录如果包含 init.py 文件,那么它就是一个Python包。

假设有一个包 mypackage,其结构如下:

mypackage/  
    __init__.py  
    module1.py  
    module2.py

init.py 中,可以定义包的导出接口,以便其他人使用时更加方便。

例如:

# __init__.py  
from .module1 import function1  
from .module2 import function2

这样,用户可以直接导入包中的函数:

from mypackage import function1, function2  
function1()  
function2()

发布和安装包

如果你开发了一个有用的包,可以将其发布到 Python 包索引(PyPI),让其他人能够通过 pip install package_name 安装使用。

参考 PyPI 的官方文档,了解如何发布你的包。

6. 异常处理

异常处理用于管理程序运行时可能出现的错误和异常,确保程序在遇到意外情况时不会崩溃,而是能够优雅地处理问题。

try…except 块

这是最基本的异常处理结构。当程序尝试执行某些代码(位于 try 块中)时,如果发生异常,将执行对应的 except 块中的代码。

try:  
    # 可能会抛出异常的代码  
    result = 10 / 0  
except ZeroDivisionError:  
    print("不能除以零!")  
# 输出:不能除以零!

多个 except 分支

可以根据不同的异常类型,提供不同的处理方式。

try:  
    x = int(input("请输入一个整数:"))  
except ValueError:  
    print("您输入的不是整数。")  
except EOFError:  
    print("输入过程中发生了EOF错误。")  
except:  
    print("发生了其他异常。")

else 子句

与 try 结合使用,可以在没有异常发生时执行特定的代码。

try:  
    result = 10 / 2  
except ZeroDivisionError:  
    print("错误:除数为零。")  
else:  
    print("没有发生异常,结果为:", result)  
# 输出:没有发生异常,结果为:5.0

finally 子句

无论是否发生异常,finally 块的代码总是会被执行,适合释放资源或进行清理操作。

try:  
    file = open("data.txt", "r")  
except FileNotFoundError:  
    print("文件未找到。")  
else:  
    content = file.read()  
    print("文件内容:", content)  
finally:  
    if 'file' in locals():  
        file.close()  
        print("文件已关闭。")

抛出异常

使用 raise 语句可以主动抛出异常,通常用于自定义异常或强制执行某些条件。

def check_age(age):  
    if age < 0:  
        raise ValueError("年龄不能是负数。")  
    print(f"您的年龄是 {age}。")  

try:  
    check_age(-5)  
except ValueError as e:  
    print(e)  
# 输出:年龄不能是负数。

自定义异常

可以通过继承 Exception 类,创建自定义的异常类型。

class InsufficientBalanceError(Exception):  
    pass  

class BankAccount:  
    def __init__(self, balance=0):  
        self.balance = balance  
    
    def withdraw(self, amount):  
        if amount > self.balance:  
            raise InsufficientBalanceError("余额不足。")  
        self.balance -= amount  
        print(f"取款金额:{amount}, 剩余余额:{self.balance}")  

try:  
    account = BankAccount(100)  
    account.withdraw(150)  
except InsufficientBalanceError as e:  
    print(e)  
# 输出:余额不足。

常见内置异常

Python提供了许多内置的异常类型,常见的包括:

  • SyntaxError:语法错误。
  • TypeError:类型错误。
  • ValueError:值错误。
  • ZeroDivisionError:除以零错误。
  • FileNotFoundError:文件未找到。
  • PermissionError:权限错误。
  • IndexError:索引错误。
  • KeyError:字典中没有该键。
  • AttributeError:对象没有该属性或方法。
  • ImportError:导入错误。

异常的优先级

捕获异常时,具体的异常类型应该放在更通用的异常类型的前面。例如,先捕获 ZeroDivisionError,再捕获通用的 Exception。

try:  
    10 / 0  
except ZeroDivisionError:  
    print("无法除以零。")  
except Exception:  
    print("发生了其他异常。")

7. 文件和输入输出

文件操作和输入输出是编程中非常重要的环节,涉及与外部世界的交互。

输入(input 函数)

从标准输入读取用户输入的内容。

name = input("请告诉我你的名字:")  
print("你好,", name)

输出(print 函数)

将内容输出到标准输出。

print("Hello, world!")  # 输出:Hello, world!  
print("多个", "参数", "用逗号分隔")  # 输出:多个 参数 用逗号分隔  
print("拼接", "字符串", end="")  # 输出:拼接字符串  
print("转义字符\n换行")  
# 输出:  
# 转义字符  
# 换行

文件操作

在Python中,使用 open() 函数打开文件,并进行读写操作。文件操作完成后,应及时关闭文件以释放资源。

# 写入文件  
with open("example.txt", "w") as file:  
    file.write("Hello, world!")  

# 读取文件  
with open("example.txt", "r") as file:  
    content = file.read()  
    print(content)  # 输出:Hello, world!
文件模式

open() 函数的第二个参数是文件模式,常见的有:

模式描述
r以只读模式打开 (默认)
w以只写模式打开,会覆盖已有内容
a以附加模式打开,写入时在末尾添加
x创建一个新文件并打开,用于写入
b二进制模式
t文本模式(默认)
+更新模式(读和写)

例如:

  • r+:读写模式。
  • rb:以二进制模式只读。
  • w+:读写模式,会覆盖已有内容。
  • ab:以二进制模式追加内容。
文件对象的方法
  • read(): 读取整个文件内容。
  • readline(): 读取一行内容。
  • readlines(): 读取所有行,返回一个列表。
  • write(): 写入内容到文件。
  • writelines(): 写入多行内容。
  • seek(): 移动文件指针到指定位置。
  • close(): 关闭文件。
with open("numbers.txt", "w") as file:  
    file.write("1\n2\n3\n4\n5\n")  

with open("numbers.txt", "r") as file:  
    lines = file.readlines()  
    for line in lines:  
        print(line.strip())  
# 输出:  
# 1  
# 2  
# 3  
# 4  
# 5
使用 with 语句

with 语句能够自动处理文件的关闭,无论是否发生异常,都确保文件被正确关闭。

标准流

Python提供了三个标准流:

  • sys.stdin:标准输入。
  • sys.stdout:标准输出。
  • sys.stderr:标准错误输出。
import sys  

print("标准输出", file=sys.stdout)  
print("标准错误", file=sys.stderr)

命令行参数

使用 sys.argv 可以访问命令行传递的参数。

import sys  

def main():  
    if len(sys.argv) > 1:  
        print(f"你传递了以下参数:{sys.argv[1:]}")  
    else:  
        print("没有传递参数。")  

if __name__ == "__main__":  
    main()

运行脚本时,可以在命令行中传递参数:

python script.py apple banana  

格式化输出

使用 format() 方法或 f-strings 来格式化输出。

name = "Bob"  
age = 30  
# 使用 format()  
print("我叫{0}, 年龄{1}.".format(name, age))  
# 使用 f-string  
print(f"我叫{name}, 年龄{age}.")  
# 输出:  
# 我叫Bob, 年龄30.

读写CSV文件

Python的 csv 模块提供了方便的方法来处理CSV格式的文件。

import csv  

# 写入CSV文件  
with open("data.csv", "w", newline="") as file:  
    writer = csv.writer(file)  
    writer.writerow(["Name", "Age", "City"])  
    writer.writerow(["Alice", 25, "New York"])  
    writer.writerow(["Bob", 30, "Los Angeles"])  

# 读取CSV文件  
with open("data.csv", "r") as file:  
    reader = csv.reader(file)  
    for row in reader:  
        print(row)  
# 输出:  
# ['Name', 'Age', 'City']  
# ['Alice', '25', 'New York']  
# ['Bob', '30', 'Los Angeles']

读写JSON数据

使用 json 模块可以轻松地在Python数据结构与JSON格式之间进行转换。

import json  

# 写入JSON文件  
data = {  
    "name": "John",  
    "age": 30,  
    "city": "London"  
}  

with open("data.json", "w") as file:  
    json.dump(data, file)  

# 读取JSON文件  
with open("data.json", "r") as file:  
    loaded_data = json.load(file)  
    print(loaded_data)  
# 输出:{'name': 'John', 'age': 30, 'city': 'London'}

对象数据序列化与反序列化

通过pickle模块可以实现直接将数据序列化与反序列化。

import pickle

x, y = 1, 2
s = "python"
t = (1,2,3)
l = ["hello", "world"]
d = {"A":100, "B":101}

with open("data.pkl", "wb") as f:
    pickle.dump((x,y,s,t,l,d),f)


with open("data.pkl", "rb") as f:
    x1, x2, xs, xt, xl, xd = pickle.load(f)
    print(x1, x2, xs, xt, xl, xd, sep="\n")
# 输出:
1
2
python
(1, 2, 3)
['hello', 'world']
{'A': 100, 'B': 101}

8. 面向对象编程

面向对象编程(OOP)是一种围绕“对象”和“类”来设计和组织软件的范式。Python作为一个多范式编程语言,全面支持OOP。

类与对象

  • 类(class):是对象的蓝图或模板,定义了对象的属性和方法。
  • 对象(object):是类的具体实例,具有独立的属性值。
class Person:  
    def __init__(self, name, age):  
        self.name = name  
        self.age = age  

    def greet(self):  
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")  

# 创建对象  
alice = Person("Alice", 25)  
alice.greet()  
# 输出:Hello, my name is Alice and I am 25 years old.

构造函数(init 方法)

init 方法是类的特殊方法,用于初始化新创建的对象。

class Car:  
    def __init__(self, brand, model, year):  
        self.brand = brand  
        self.model = model  
        self.year = year  
        self.mileage = 0  

    def drive(self, miles):  
        self.mileage += miles  

my_car = Car("Toyota", "Corolla", 2020)  
print(my_car.brand)  # 输出:Toyota  
my_car.drive(100)  
print(my_car.mileage)  # 输出:100

属性与方法

对象的属性是与对象相关的数据,方法是对象可以执行的动作。

class BankAccount:  
    def __init__(self, account_number, balance=0):  
        self.account_number = account_number  
        self._balance = balance  # 使用单前缀表示受保护的属性  

    def deposit(self, amount):  
        if amount > 0:  
            self._balance += amount  
            print(f"存入{amount}, 剩余余额{self._balance}")  
        else:  
            print("存入金额必须为正数。")  

    def get_balance(self):  
        return self._balance  

account = BankAccount("1234567890", 1000)  
account.deposit(500)  # 输出:存入500, 剩余余额1500  
print(account.get_balance())  # 输出:1500

继承

继承允许一个类(子类)继承另一个类(超类)的属性和方法,并可以添加新的功能或覆盖超类的功能。

class Animal:  
    def __init__(self, name):  
        self.name = name  

    def eat(self):  
        print(f"{self.name}正在吃。")  

class Dog(Animal):  
    def __init__(self, name, breed):  
        super().__init__(name)  
        self.breed = breed  

    def bark(self):  
        print(f"{self.name}在叫。")  

my_dog = Dog("Buddy", "Golden Retriever")  
my_dog.eat()       # 输出:Buddy正在吃。  
my_dog.bark()      # 输出:Buddy在叫。  
print(my_dog.breed)  # 输出:Golden Retriever

多态

多态是指不同类的对象对同一消息做出不同的响应。Python通过方法的动态绑定支持多态。

class Shape:  
    def area(self):  
        pass  

class Square(Shape):  
    def __init__(self, side):  
        self.side = side  

    def area(self):  
        return self.side ** 2  

class Circle(Shape):  
    def __init__(self, radius):  
        self.radius = radius  

    def area(self):  
        return 3.14159 * self.radius ** 2  

square = Square(4)  
circle = Circle(3)  

shapes = [square, circle]  
for shape in shapes:  
    print(f"面积:{shape.area()}")  
# 输出:  
# 面积:16  
# 面积:28.27431

抽象类与接口

通过 abc(Abstract Base Classes,抽象基类)模块,可以定义抽象基类和抽象方法,强制子类实现特定的接口。

from abc import ABC, abstractmethod  

class AbstractPerson(ABC):  
    @abstractmethod  
    def get_name(self):  
        pass  

    @abstractmethod  
    def get_age(self):  
        pass  

class Employee(AbstractPerson):  
    def __init__(self, name, age, employee_id):  
        self.name = name  
        self.age = age  
        self.employee_id = employee_id  

    def get_name(self):  
        return self.name  

    def get_age(self):  
        return self.age  

try:  
    person = AbstractPerson()  # 会引发TypeError,因为无法直接实例化抽象类  
except TypeError:  
    print("不能直接实例化抽象类。")  

emp = Employee("Bob", 30, "E12345")  
print(emp.get_name())  # 输出:Bob  
print(emp.get_age())   # 输出:30

类方法、静态方法与实例方法

  • 实例方法:作用于实例,第一个参数为 self。
  • 类方法:作用于类,使用装饰器 @classmethod,第一个参数为 cls。
  • 静态方法:不作用于实例或类,使用装饰器 @staticmethod。
class MyClass:  
    # 实例方法  
    def instance_method(self):  
        return "这是实例方法。"  
    
    # 类方法  
    @classmethod  
    def class_method(cls):  
        return "这是类方法。"  
    
    # 静态方法  
    @staticmethod  
    def static_method():  
        return "这是静态方法。"  

obj = MyClass()  

print(obj.instance_method())      # 输出:这是实例方法。  
print(MyClass.class_method())     # 输出:这是类方法。  
print(MyClass.static_method())    # 输出:这是静态方法。  
print(obj.static_method())        # 输出:这是静态方法。

属性装饰器

使用 @property 装饰器,可以为类属性添加 getter、setter 方法,增加灵活性。

class Student:  
    def __init__(self, name, score):  
        self._name = name  
        self._score = score  

    @property  
    def name(self):  
        return self._name  

    @name.setter  
    def name(self, value):  
        if isinstance(value, str):  
            self._name = value  
        else:  
            raise TypeError("名字必须是字符串。")  

    @property  
    def score(self):  
        return self._score  

    @score.setter  
    def score(self, value):  
        if isinstance(value, (int, float)) and value >= 0:  
            self._score = value  
        else:  
            raise ValueError("分数必须是大于等于零的数。")  

student = Student("Alice", 85)  
print(student.name)  # 输出:Alice  
print(student.score)  # 输出:85  

student.name = "Bob"  
try:  
    student.score = -5  
except ValueError as e:  
    print(e)  
# 输出:分数必须是大于等于零的数。

魔术方法

魔术方法是特殊的双下划线方法,用于定制类的行为,例如 init, str, repr, len 等。

class Vector:  
    def __init__(self, x, y):  
        self.x = x  
        self.y = y  

    def __add__(self, other):  
        return Vector(self.x + other.x, self.y + other.y)  

    def __str__(self):  
        return f"({self.x}, {self.y})"  

    def __repr__(self):  
        return f"Vector({self.x}, {self.y})"  

    def __eq__(self, other):  
        return self.x == other.x and self.y == other.y  

vector1 = Vector(2, 3)  
vector2 = Vector(4, 5)  

vector3 = vector1 + vector2  
print(vector3)  # 输出:(6, 8)  
print(repr(vector3))  # 输出:Vector(6, 8)  
print(vector3 == Vector(6, 8))  # 输出:True

元类

元类是用于创建类的类。默认情况下,所有类都是由 type 创建的,可以通过自定义元类来控制类的创建过程。

class Meta(type):  
    def __new__(cls, name, bases, namespace):  
        print(f"正在创建类:{name}")  
        return super().__new__(cls, name, bases, namespace)  

class MyClass(metaclass=Meta):  
    pass  

obj = MyClass()  
# 输出:  
# 正在创建类:MyClass

9. 高级语法

Python还有一些高级语法特性,可以用来编写更简洁、更高效的代码。

列表推导式(List Comprehensions)

用于快速创建列表,通过对可迭代对象的每个元素应用表达式。

numbers = [1, 2, 3, 4, 5]  
squared_numbers = [n**2 for n in numbers]  
print(squared_numbers)  # 输出:[1, 4, 9, 16, 25]  

even_numbers = [n for n in range(1, 11) if n % 2 == 0]  
print(even_numbers)  # 输出:[2, 4, 6, 8, 10]  

pairs = [(x, y) for x in range(1, 4) for y in range(1, 4) if x < y]  
print(pairs)  # 输出:[(1, 2), (1, 3), (2, 3)]

生成器与生成器表达式

生成器是一种特殊的迭代器,可以通过函数和 yield 关键字创建。生成器表达式则是列表推导式的生成器版本,以 () 表示。

def infinite_sequence():  
    num = 0  
    while True:  
        yield num  
        num += 1  

gen = infinite_sequence()  
for _ in range(5):  
    print(next(gen))  # 输出:0,1,2,3,4  

numbers = [1, 2, 3, 4, 5]  
squares = (n**2 for n in numbers)  
for square in squares:  
    print(square)  
# 输出:  
# 1  
# 4  
# 9  
# 16  
# 25

装饰器(Decorators)

装饰器用于包装函数或方法,扩展其功能。

def my_decorator(func):  
    def wrapper():  
        print("Something is happening before the function is called.")  
        func()  
        print("Something is happening after the function is called.")  
    return wrapper  

@my_decorator  
def say_hello():  
    print("Hello!")  

say_hello()  
# 输出:  
# Something is happening before the function is called.  
# Hello!  
# Something is happening after the function is called.

上下文管理器(Context Manager)

使用 contextlib.contextmanager 创建自定义的上下文管理器,通过 with 语句管理资源。

from contextlib import contextmanager  

@contextmanager  
def open_file(name):  
    try:  
        file = open(name, "r")  
        yield file  
    finally:  
        file.close()  

with open_file("example.txt") as file:  
    content = file.read()  
    print(content)

异步编程(asyncio)

在Python 3.5及以后版本,引入了asyncio模块,支持异步编程。

import asyncio  

async def my_function():  
    await asyncio.sleep(1)  
    return "函数执行完毕。"  

async def main():  
    print("开始执行。")  
    result = await my_function()  
    print(result)  

asyncio.run(main())  
# 输出:  
# 开始执行。  
# 函数执行完毕。

并发与多线程

使用 threading 模块可以实现多线程编程,但需要注意线程安全的问题。

import threading  
import time  

def print_numbers():  
    for i in range(5):  
        time.sleep(1)  
        print(i)  

def print_letters():  
    for c in 'ABCDE':  
        time.sleep(1)  
        print(c)  

thread1 = threading.Thread(target=print_numbers)  
thread2 = threading.Thread(target=print_letters)  

thread1.start()  
thread2.start()  

thread1.join()  
thread2.join()  

# 输出:  
# 0  
# A  
# 1  
# B  
# 2  
# C  
# 3  
# D  
# 4  
# E

正则表达式

使用 re 模块可以进行复杂的字符串匹配和处理。

import re  

pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"  
email = "[email protected]"  

if re.match(pattern, email):  
    print("有效的电子邮件地址。")  
else:  
    print("无效的电子邮件地址。")  
# 输出:有效的电子邮件地址。  

text = "The quick brown fox jumps over the lazy dog."  
matches = re.findall(r"\b\w+\b", text)  
print(matches)  
# 输出:['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

闭包(Closures)

闭包是指函数内部定义的函数,可以访问外部函数的变量。

def outer_function():  
    def inner_function():  
        return "这是一个闭包。"  
    return inner_function  

closure = outer_function()  
print(closure())  
# 输出:这是一个闭包。

lambda 函数

匿名函数,适用于简单的逻辑。

sum = lambda x, y: x + y  
print(sum(5, 3))  # 输出:8  

numbers = [1, 2, 3, 4, 5]  
squared_numbers = list(map(lambda x: x**2, numbers))  
print(squared_numbers)  # 输出:[1, 4, 9, 16, 25]

10. 常用内置函数

Python提供了许多内置函数,能够帮助你快速完成各种操作。

help()

显示对象的文档字符串或使用说明。

help(len)  
# 输出:len(iterable) -> int  
# 定义为长度返回对象的长度。 

dir()

列出对象的所有属性和方法。

dir(str)  
# 输出:['__add__', '__class__', '__contains__', ..., 'upper', 'zfill']  

type()

返回对象的类型。

print(type(123))  # 输出:<class 'int'>  
print(type("abc"))  # 输出:<class 'str'>  
print(type([1, 2, 3]))  # 输出:<class 'list'>  

id()

返回对象的唯一标识符。

a = 5  
b = 5  
c = 256  
print(id(a) == id(b))  # 输出:True  
print(id(a) == id(c))  # 输出:False  

len()

返回对象的长度或元素个数。

print(len("hello"))  # 输出:5  
print(len([1, 2, 3]))  # 输出:3  
print(len({"a": 1, "b": 2}))  # 输出:2  

range()

生成一个可迭代的数值序列。

for i in range(5):  
    print(i)  
# 输出:  
# 0  
# 1  
# 2  
# 3  
# 4  

numbers = list(range(1, 5))  
print(numbers)  # 输出:[1, 2, 3, 4]  

enumerate()

遍历可迭代对象的同时,获取索引和元素。

fruits = ['apple', 'banana', 'cherry']  
for index, fruit in enumerate(fruits):  
    print(f"第{index}个水果是{fruit}")  
# 输出:  
# 第0个水果是apple  
# 第1个水果是banana  
# 第2个水果是cherry  

map()、filter()、reduce()

用于处理可迭代对象的高级函数。

# map  
squared = list(map(lambda x: x**2, [1, 2, 3, 4]))  
print(squared)  # 输出:[1, 4, 9, 16]  

# filter  
def is_even(x):  
    return x % 2 == 0  
even_numbers = list(filter(is_even, range(10)))  
print(even_numbers)  # 输出:[0, 2, 4, 6, 8]  

# reduce  
from functools import reduce  
numbers = [1, 2, 3, 4, 5]  
product = reduce(lambda x, y: x * y, numbers)  
print(product)  # 输出:120  

zip()

将多个可迭代对象的元素配对。

list1 = [1, 2, 3]  
list2 = ['a', 'b', 'c']  
combined = zip(list1, list2)  
for pair in combined:  
    print(pair)  
# 输出:  
# (1, 'a')  
# (2, 'b')  
# (3, 'c')  

any() 和 all()

用于判断可迭代对象的元素是否满足某些条件。

numbers = [1, 2, 3]  
print(any(x > 2 for x in numbers))  # 输出:True  
print(all(x > 2 for x in numbers))  # 输出:False  

max() 和 min()

返回可迭代对象中的最大值和最小值。

numbers = [4, 2, 9, 6]  
print(max(numbers))  # 输出:9  
print(min(numbers))  # 输出:2  

sum()

计算可迭代对象中所有元素的总和。

numbers = [1, 2, 3, 4, 5]  
print(sum(numbers))  # 输出:15  

sorted()

对可迭代对象进行排序。

numbers = [3, 1, 4, 2]  
print(sorted(numbers))  # 输出:[1, 2, 3, 4]  
print(sorted(numbers, reverse=True))  # 输出:[4, 3, 2, 1]  

strings = ["banana", "apple", "cherry"]  
print(sorted(strings))  # 输出:['apple', 'banana', 'cherry']  

round()

将数值四舍五入到指定的位数。

print(round(3.14159, 2))  # 输出:3.14  
print(round(2.71828, 1))  # 输出:2.7  

11. 常见的编程错误与调试

在编程过程中,难免会遇到各种错误。了解常见错误类型和掌握基本的调试技巧,可以帮助你更高效地解决问题。

语法错误(SyntaxError)

通常是由于代码不符合Python的语法规则导致的。

# 错误示例:缺少冒号  
if True  
    print("True")  

# 正确示例:  
if True:  
    print("True")  

逻辑错误

代码语法正确,但执行结果与预期不符。这类错误往往需要通过调试来发现和修复。

# 错误示例:计算乘法时误用了加法  
def multiply(a, b):  
    return a + b  

# 正确示例:  
def multiply(a, b):  
    return a * b  

运行时错误

程序在执行过程中发生的错误,如除以零、文件未找到等。

# 错误示例:除以零  
try:  
    print(10 / 0)  
except ZeroDivisionError:  
    print("不能除以零!")  

调试技巧

  • 打印中间结果:通过 print() 函数输出关键变量的值,了解程序的执行情况。
  • 使用调试器:大多数 IDE 都内置了调试器,如 PyCharm 的 Debugger,可以设置断点逐步执行代码。
  • 日志记录:使用 logging 模块记录程序运行时的信息,帮助定位问题。
  • 查看错误信息:详细阅读错误提示,了解错误的类型和发生的位置。

常见错误类型

  • TypeError:操作不支持的类型。
  • ValueError:函数或操作接收了不可接受的值。
  • IndexError:序列下标超出范围。
  • KeyError:字典中没有该键。
  • AttributeError:对象没有该属性或方法。
  • ImportError:导入模块失败。

异常处理

合理使用 try…except 块来捕获和处理异常,避免程序因错误而崩溃。

try:  
    # 可能会抛出异常的代码  
    result = 10 / 0  
except ZeroDivisionError:  
    print("错误:除数为零。")  
else:  
    print("没有发生异常,结果为:", result)  
finally:  
    print("不管是否发生异常,这里都会执行。")  

12. 常见的Python最佳实践

在编写Python代码时,遵循一些最佳实践能够使你的代码更可读、更可维护和更高效。

代码风格

遵循PEP 8(Python Enhancement Proposal 8),这是Python官方的代码风格指南。
使用明确的变量名,避免使用单字母变量名(如 x、y)。
保持代码行的长度在79字符以内。
使用空行分隔代码块,提高可读性。

注释与文档

使用清晰的注释解释复杂的代码部分。
为函数、类和模块编写文档字符串,说明其用途、参数和返回值。
避免冗余的注释,注释应补充代码的信息,而不是重复代码的内容。

避免全局变量

尽量减少对全局变量的使用,使用全局变量可能会引入意外的副作用和调试困难。

# 不推荐  
global_variable = 0  

def modify_global():  
    global global_variable  
    global_variable += 1  

# 推荐  
class GameState:  
    def __init__(self):  
        self.score = 0  

    def increase_score(self):  
        self.score += 1

优先使用异常而非返回值

在处理错误条件时,优先使用异常而非返回特殊值(如 None 或 -1),这样可以使代码更清晰,错误处理更明确。

# 不推荐  
def divide(a, b):  
    if b == 0:  
        return None  
    return a / b  

result = divide(10, 0)  
if result is None:  
    print("错误:除数为零。")  

# 推荐  
def divide(a, b):  
    if b == 0:  
        raise ZeroDivisionError("除数为零。")  
    return a / b  

try:  
    divide(10, 0)  
except ZeroDivisionError as e:  
    print(e)

单责任原则

每个函数或方法应该有且仅有一个责任,避免单一函数处理多个不相关的任务。

# 不推荐  
def process_data(data):  
    # 加载数据  
    # 进行计算  
    # 生成报告  
    pass  

# 推荐  
def load_data():  
    # 加载数据  
    pass  

def calculate(data):  
    # 进行计算  
    pass  

def generate_report(data):  
    # 生成报告  
    pass  

data = load_data()  
result = calculate(data)  
generate_report(result)

使用列表推导式和生成器表达式

列表推导式和生成器表达式可以使代码更简洁高效,避免使用冗长的循环。

# 不推荐  
squared_numbers = []  
for number in numbers:  
    squared = number ** 2  
    squared_numbers.append(squared)  

# 推荐  
squared_numbers = [n ** 2 for n in numbers]

测试你的代码

编写单元测试,确保代码在各种情况下都能正常工作,特别是在对代码进行修改和重构时。

import unittest  

def add(a, b):  
    return a + b  

class TestAddFunction(unittest.TestCase):  
    def test_add(self):  
        self.assertEqual(add(1, 2), 3)  
        self.assertEqual(add(-1, 1), 0)  
        self.assertEqual(add(-1, -1), -2)  
        with self.assertRaises(TypeError):  
            add(1, "a")  

if __name__ == "__main__":  
    unittest.main()

使用版本控制

无论是个人项目还是团队项目,都应使用版本控制工具(如Git)来管理代码的更改历史,避免代码丢失和协作困难。

git init  
git add .  
git commit -m "Initial commit."

保持代码的可读性

编写代码时,优先考虑可读性。使用清晰的变量名、适当的注释和合理的代码结构,让代码“自解释”。

# 不推荐  
a = 3600 + 60*60  

# 推荐  
TOTAL_SECONDS = 3600  # 一小时  
FULL_DAY_HOURS = 24  
full_day_seconds = TOTAL_SECONDS * FULL_DAY_HOURS

13. 总结

Python的基础语法涵盖了变量、数据类型、运算符、控制流、函数、模块、异常处理、文件操作等多个方面。通过实践和不断的学习,你可以逐步掌握这些语法要素,并将其应用到实际编程任务中。同时,遵循最佳实践和开发工具的使用,将帮助你成为一名更高效、更专业的Python开发者。编程是一个需要不断实践和探索的过程,保持学习的热情和解决问题的兴趣,你会在Python的世界里越走越远!

;