注:本文为作者原创文章,学习时归纳总结,以知识点+代码的形式纪录,通过目录可以很快捷的查找到知识点对应内容,若有不足之处或疑问可以指出,禁止转载,谢谢
1.注释:
1.1单行注释
#
# Hello
1.2多行注释
"""......"""
'''.....'''
"""
Hello
"""
'''
World
'''
2.标识符:
命名规则:
- 不能和python关键字( 编译器不会检查 )
- 不能以数字开头
- 由数字,字母,下划线,汉字组成
- 区分大小写
_abc=123
a123b_="abc"
3.强制缩进:
表示代码块
if True:
print("This is inside the if block") # 这里使用了 4 个空格的缩进
print("Still inside")
else:
print("This is the else block")
4.多行语句:
语句过长
使用\表示一条跨多行的语句
在[]和{}和()中不需要
# 普通情况下使用 \ 来换行
long_statement = "This is a very long statement and " \
"needs to be split across multiple lines"
# 在 [] 中不需要使用 \
my_list = [1, 2, 3,
4, 5, 6]
# 在 {} 中不需要使用 \
my_dict = {
'key1': 'value1',
'key2': 'value2'
}
# 在 () 中不需要使用 \
my_tuple = (1, 2, 3,
4, 5, 6)
5.模块:
- 全部导入 import 模块名 [as 别名] -> 声明了别名只能用别名
- 从指定模块中导入全部 from模块名 import *
- 导入指定成员 from 模块名 import 成员名 [as 别名] from math import sqrt
- 2和3调用函数或方法不需要使用模块名
-
# 全部导入并使用别名 import math as m print(m.sqrt(4)) # 从指定模块中导入全部 from math import * print(sqrt(9)) # 导入指定成员并使用别名 from math import sqrt as square_root print(square_root(16))
6.math库
6.1 常数
pi e inf正无穷大
6.2 floor(x)
向下取整(小于等于x的最大整数,正数舍去小数部分)
6.3 ceil(x)
向上取整
6.4 fabs(x)
绝对值 abs(x)
6.5 sqrt(x)
开根号
import math
# 常数 pi 和 e
print("Pi:", math.pi) # 输出: Pi: 3.141592653589793
print("E:", math.e) # 输出: E: 2.718281828459045
# floor 函数
print("Floor of 3.8:", math.floor(3.8)) # 输出: Floor of 3.8: 3
# ceil 函数
print("Ceil of 3.2:", math.ceil(3.2)) # 输出: Ceil of 3.2: 4
# fabs 函数
print("Fabs of -5.6:", math.fabs(-5.6)) # 输出: Fabs of -5.6: 5.6
# abs 函数
print("Abs of -7.2:", abs(-7.2)) # 输出: Abs of -7.2: 7.2
# sqrt 函数
print("Sqrt of 16:", math.sqrt(16)) # 输出: Sqrt of 16: 4.0
7.random库
7.1 (random.)random()
生成0.0-1.0 的随即小数
7.2 (random.)randint(a,b)
[a,b]随机数
7.3 randrange(start,stop,[step])
生成[start,stop)步长为step的随机数
7.4 uniform(a,b)
生成[a,b]随机实数
import random
# random() 函数
print("Random number between 0.0 and 1.0:", random.random()) # 输出: 一个在 0.0 到 1.0 之间的随机小数
# randint(a, b) 函数
print("Random integer between 1 and 5:", random.randint(1, 5)) # 输出: 一个在 1 到 5 之间(包括 1 和 5)的随机整数
# randrange(start, stop, [step]) 函数
print("Random number from randrange(1, 10, 2):", random.randrange(1, 10, 2)) # 输出: 1 到 10 之间(不包括 10)步长为 2 的随机数,如 1、3、5、7、9 中的一个
# uniform(a, b) 函数
print("Random real number between 2.0 and 5.0:", random.uniform(2.0, 5.0)) # 输出: 一个在 2.0 到 5.0 之间的随机实数
8.数据类型
8.1 数值类型:
int float bool complex
8.2 组合类型:
序列(列表list 元组tuple 字符串str) 集合set 字典dict
8.3 整型:
二进制0b/0B 八进制0o 十六进制是0x 十进制
8.4 浮点型:
十进制 科学计数法1.23e5=1.23E5=1.23*10^5
8.5 复数型:
Y=3.2+4.5j (real=3.2 imag=4.5)
8.6 布尔型:
True->1 False->0
# 整型示例
decimal_int = 10
binary_int = 0b1010
octal_int = 0o12
hexadecimal_int = 0x10
# 浮点型示例
decimal_float = 3.14
scientific_float = 1.23e5
# 复数型示例
complex_number = 3.2 + 4.5j
# 布尔型示例
bool_true = True
bool_false = False
# 序列类型 - 列表
list_example = [1, 2, 3, 4, 5]
# 序列类型 - 元组
tuple_example = (6, 7, 8, 9, 10)
# 序列类型 - 字符串
string_example = "Hello, World!"
# 集合
set_example = {11, 12, 13, 14, 15}
# 字典
dict_example = {'key1': 1, 'key2': 2}
8.7 列表
[]
列表中的元素可以是不同的数据类型。
运算符:
+
:用于连接两个列表。*
:用于重复列表。in
:判断元素是否在列表中。not in
:判断元素是否不在列表中。
操作函数:
len(List)
:返回列表的长度。max(List)
:返回列表中的最大元素。min(List)
:返回列表中的最小元素。list(seq)
:将其他可迭代对象转换为列表。
操作方法:
List.append(obj)
:在列表末尾添加一个对象。List.count(obj)
:统计obj
在列表中出现的次数。List.extend(seq)
:在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)。List.index(obj)
:返回列表中指定元素的下标(整数)。List.insert(index, obj)
:将对象插入列表指定位置。List.pop([index=-1])
:移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。List.remove(obj)
:移除列表中第一个匹配到的指定元素。List.reverse()
:将列表中的元素反向排列。List.sort(key=None, reverse=False)
:对原列表进行排序。key
用于指定排序的依据,reverse=True
为降序,默认reverse=False
为升序。List.clear()
:清空列表中的所有元素。List.copy()
:复制列表。
my_list = [1, 2.5, 'hello', True]
# 运算符
print(1 in my_list) # 输出: True
print('world' not in my_list) # 输出: True
new_list = my_list + [5, 6]
print(new_list) # 输出: [1, 2.5, 'hello', True, 5, 6]
multiple_list = my_list * 2
print(multiple_list) # 输出: [1, 2.5, 'hello', True, 1, 2.5, 'hello', True]
# 操作函数
print(len(my_list)) # 输出: 4
print(max(my_list)) # 错误,不同数据类型无法直接比较最大值
print(min(my_list)) # 错误,不同数据类型无法直接比较最小值
new_list2 = list((1, 2, 3))
print(new_list2) # 输出: [1, 2, 3]
# 操作方法
my_list.append('world')
print(my_list) # 输出: [1, 2.5, 'hello', True, 'world']
print(my_list.count(1)) # 输出: 1
my_list.extend([7, 8])
print(my_list) # 输出: [1, 2.5, 'hello', True, 'world', 7, 8]
print(my_list.index('hello')) # 输出: 2
my_list.insert(1, 'new_item')
print(my_list) # 输出: [1, 'new_item', 2.5, 'hello', True, 'world', 7, 8]
popped_item = my_list.pop()
print(popped_item) # 输出: 8
print(my_list) # 输出: [1, 'new_item', 2.5, 'hello', True, 'world', 7]
my_list.remove('new_item')
print(my_list) # 输出: [1, 2.5, 'hello', True, 'world', 7]
my_list.reverse()
print(my_list) # 输出: [7, 'world', True, 'hello', 2.5, 1]
my_list.sort() # 错误,不同数据类型无法直接排序
my_list.clear()
print(my_list) # 输出: []
copy_list = my_list.copy()
print(copy_list) # 输出: []
8.8 元组
()
元组与列表相似,但元组中的元素不能修改。
创建元组时,如果只有一个元素,需要在元素后面加上逗号,例如:tuple2 = (5,)
运算符:
+
:用于连接两个元组。*
:用于重复元组。in
:判断元素是否在元组中。not in
:判断元素是否不在元组中。
操作函数:
len(Tuple)
:返回元组的长度。max(Tuple)
:返回元组中的最大元素。min(Tuple)
:返回元组中的最小元素。sum(Tuple)
:返回元组中所有元素的总和。tuple(seq)
:将其他可迭代对象转换为元组。
操作方法:
Tuple.count(obj)
:统计指定元素在元组中出现的次数。Tuple.index(obj)
:返回指定元素在元组中的下标。
tuple1 = (1, 2, 3, 'hello')
tuple2 = (5,)
# 运算符
print(1 in tuple1) # 输出: True
print('world' not in tuple1) # 输出: True
new_tuple = tuple1 + tuple2
print(new_tuple) # 输出: (1, 2, 3, 'hello', 5)
multiple_tuple = tuple1 * 2
print(multiple_tuple) # 输出: (1, 2, 3, 'hello', 1, 2, 3, 'hello')
# 操作函数
print(len(tuple1)) # 输出: 4
print(max(tuple1)) # 错误,不同数据类型无法直接比较最大值
print(min(tuple1)) # 错误,不同数据类型无法直接比较最小值
print(sum((1, 2, 3))) # 输出: 6
new_tuple2 = tuple([1, 2, 3])
print(new_tuple2) # 输出: (1, 2, 3)
# 操作方法
print(tuple1.count(1)) # 输出: 1
print(tuple1.index('hello')) # 输出: 3
8.9 字符串:
8.9.1 定义
在 Python 中没有字符类型
使用 ' '
、" "
、''' '''
来定义字符串。
8.9.2 转义字符
-
\t
:制表符,8 位栏宽 \’
:表示'
\”
:表示"
\\
:表示\
\n
:换行\ooo
:八进制数\xhh
:十六进制
8.9.3 原始字符串
字符串前加 r/R
,字符串中所有字符呈现原始状态。
8..4 字符串运算
- 比较大小:比较 Unicode 值大小,规则为大写字母 < 小写字母,数字 < 字母,英文 < 汉字。
- 连接:
s1 + s2
- 成员判断:
s1 in s2
- 索引:
s[i]
、s[-i]
- 重复:
s * n
- 相等判断:
s1 == s2
、s1!= s2
- 遍历:
for x in s1
8.9.5 字符串切片
S[i:j]
,不能修改。
8.9.6 字符串相关函数
- 字符转换:
bin(n)
、hex(n)
、oct(n)
- 基本操作:
len(s)
、max(s)
、min(s)
、sorted(s)
- 格式化:
format(s, 格式字符)
,例如format(100, 'b')
8.9.7 字符串模块
- 字母表:
ascii_letters
(英文字母表)、ascii_uppercase
(大写字母)、ascii_lowercase
(小写字母)、digits
(数字)、punctuation
(标点符号) - 判断数字:
_ in string.digits -> bool
8.9.8 字符串的拆分连接
split
和rsplit
<母串>.split(<分隔串>, n)
:分隔串默认空格,结果不包括分隔串;n
是最大拆分次数,一般返回一个列表。'A B C D'.split()
->['A', 'B', 'C', 'D']
'A,B,C,D'.split(',')
->['A', 'B', 'C', 'D']
'A B C D'.split(' ', 1)
->['A', 'B C D']
'A B C D'.rsplit(' ', 1)
->['A B C', 'D']
join
<连接串>.join(<字串序列)>
:返回字符串。A = [1, 2, 3, 4]
,':'.join(A)
->"1:2:3:4"
partition
和rpartition
<母串>.partition(<分隔串>)
:拆分一次,拆分出来的结果包括分隔串,返回一个三元组。'A B C D'.partition(' ')
->('A',' ', 'B C D')
8.9.9 字符串的查找替换
find
和rfind
:<母串>.find(<字串>, m, n)
从[m, n)
找字串,没找到返回-1
。index
和rindex
:<母串>.index(<字串>, m, n)
从[m, n)
找字串,没找到报错。count
:<母串>.count(<字串>, m, n)
计算次数。replace
:<母串>.replace(<字串>, <新串>)
替换,找不到字串不替换。
8.9.10 字符串的测试方法
isdigit()
:判断是否为数字isalpha()
:判断是否为字母/汉字isalnum
:判断是否为数字/字母/汉字isupper
:判断是否为大写islower
:判断是否为小写isspace
:判断是否为空格(换行、制表、tab)startswith(<前缀串>, m, n)
endswith(<后缀串>, m, n)
# 定义字符串
string1 = "Hello, World!"
string2 = 'Python is great!'
string3 = '''This is a multi-line string.'''
# 转义字符
print("With tab:\tTabbed output") # 输出: With tab: Tabbed output
print("With newline:\nNew line") # 输出: With newline:
# New line
# 原始字符串
print(r"With backslash: \\\") # 输出: With backslash: \\
# 字符串运算
string4 = string1 + string2 # 连接字符串
print(string4) # 输出: Hello, World!Python is great!
print('on' in string1) # 输出: True # 成员判断
print(string1[0]) # 输出: H # 索引
print(string1 * 2) # 输出: Hello, World!Hello, World! # 重复
# 字符串切片
print(string1[0:5]) # 输出: Hello # 切片
# 字符串函数
num = 10
print(bin(num)) # 输出: 0b1010
print(hex(num)) # 输出: 0xa
print(oct(num)) # 输出: 0o12
print(len(string1)) # 输出: 13 # 长度
# 字符串模块
import string
print(string.ascii_letters) # 输出: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.digits) # 输出: 0123456789
# 字符串的拆分连接
string5 = "A,B,C,D"
split_result = string5.split(',')
print(split_result) # 输出: ['A', 'B', 'C', 'D']
join_result = ':'.join(split_result)
print(join_result) # 输出: A:B:C:D
# 字符串的查找替换
string6 = "Hello, World!"
find_result = string6.find('World')
print(find_result) # 输出: 7
replace_result = string6.replace('World', 'Python')
print(replace_result) # 输出: Hello, Python!
# 字符串的测试方法
string7 = "123"
print(string7.isdigit()) # 输出: True
string8 = "Hello"
print(string8.isalpha()) # 输出: True
string9 = "Hello123"
print(string9.isalnum()) # 输出: True
string10 = "HELLO"
print(string10.isupper()) # 输出: True
string11 = "hello"
print(string11.islower()) # 输出: True
string12 = " "
print(string12.isspace()) # 输出: True
print(string1.startswith('Hello')) # 输出: True
print(string1.endswith('World!')) # 输出: True
# 字符串的对齐压缩
string13 = "Hello"
print(string13.center(10)) # 输出: Hello
print(string13.ljust(10)) # 输出: Hello
print(string13.rjust(10)) # 输出: Hello
string14 = " Hello "
print(string14.strip()) # 输出: Hello
print(string14.lstrip()) # 输出: Hello
print(string14.rstrip()) # 输出: Hello
# 字符串的大小写转换
string15 = "hello"
print(string15.upper()) # 输出: HELLO
print(string15.swapcase()) # 输出: HELLO
print(string15.capitalize()) # 输出: Hello
print(string15.title()) # 输出: Hello
8.10 集合(无序可变)
集合使用 {}
来定义。
集合的特点:
- 不能有重复元素。
- 元素的顺序是无序的。
- 不能通过下标访问元素。
运算符:
in
:判断元素是否在集合中。not in
:判断元素是否不在集合中。==
:判断两个集合是否相等。!=
:判断两个集合是否不相等。Set1 < set2
:Set1
是set2
的真子集。Set1 <= set2
:Set1
是set2
的子集。Set1 & set2
:求两个集合的交集。Set1 | set2
:求两个集合的并集。Set1 - set2
:求两个集合的差集。Set1 ^ set2
:求两个集合的对称差(不同时属于两个集合的元素)。
操作函数:
len()
:返回集合中元素的数量。min()
:返回集合中的最小元素。max()
:返回集合中的最大元素。sum()
:通常用于对集合中的数字元素求和,集合一般不用于求和操作。set()
:用于创建一个新的集合。
操作方法:
Set.add(x)
:向集合中添加单个元素x
。Set.update(x)
:添加x
为可迭代对象。Set.remove(x)
:删除集合中的元素x
,如果元素不存在会报错。Set.discard(x)
:删除集合中的元素x
,如果元素不存在不会报错。Set.pop()
:随机删除并返回集合中的一个元素。Set.clear()
:清空集合中的所有元素。Set.copy()
:复制集合。
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# 运算符
print(1 in set1) # 输出: True
print(7 not in set1) # 输出: True
print(set1 == set2) # 输出: False
print(set1!= set2) # 输出: True
print(set1 < set2) # 输出: False
print(set1 <= set2) # 输出: False
# 操作函数
print(len(set1)) # 输出: 4
print(min(set1)) # 输出: 1
print(max(set1)) # 输出: 4
print(sum(set1)) # 输出: 10
new_set = set([1, 2, 3])
print(new_set) # 输出: {1, 2, 3}
# 操作方法
set1.add(5)
print(set1) # 输出: {1, 2, 3, 4, 5}
set1.update([6, 7])
print(set1) # 输出: {1, 2, 3, 4, 5, 6, 7}
set1.remove(7)
print(set1) # 输出: {1, 2, 3, 4, 5, 6}
set1.discard(8) # 不会报错
set1.pop()
print(set1) # 随机删除一个元素并输出剩余集合
set1.clear()
print(set1) # 输出: set()
copy_set = set2.copy()
print(copy_set) # 输出: {3, 4, 5, 6}
8.11 字典:
键值对,键必须是唯一的,而且必须是不可变数据类型
注意点:
{}空字典
set()空集合
9.运算符
- %取模(求余)
- **幂运算符
- //整除运算符
- 赋值运算符 += -= /= *=
- 关系运算< > ==
- 逻辑运算符 and or not
- 成员测试运算符 in not in
- 位运算符:& | ^ ~ << >>
- 身份运算符:is not is AisB -> id(A)==id(B)是一个东西的不同名字 (A==B 值相等)
a = 10
b = 3
# 取模(求余)
print(a % b) # 输出: 1
# 幂运算符
print(a ** b) # 输出: 1000
# 整除运算符
print(a // b) # 输出: 3
# 赋值运算符
a += 5
print(a) # 输出: 15
a -= 2
print(a) # 输出: 13
a /= 2
print(a) # 输出: 6.5
a *= 3
print(a) # 输出: 19.5
# 关系运算
print(a < b) # 输出: False
print(a > b) # 输出: True
print(a == b) # 输出: False
# 逻辑运算符
c = True
d = False
print(c and d) # 输出: False
print(c or d) # 输出: True
print(not c) # 输出: False
# 成员测试运算符
list1 = [1, 2, 3]
print(2 in list1) # 输出: True
print(4 not in list1) # 输出: True
# 位运算符
e = 5 # 0101
f = 3 # 0011
print(e & f) # 输出: 1 (0001)
print(e | f) # 输出: 7 (0111)
print(e ^ f) # 输出: 6 (0110)
print(~e) # 输出: -6 (按位取反)
print(e << 2) # 输出: 20 (010100)
print(e >> 1) # 输出: 2 (0010)
# 身份运算符
x = [1, 2, 3]
y = x
z = [1, 2, 3]
print(x is y) # 输出: True
print(x is z) # 输出: False
print(x is not z) # 输出: True
10. 程序控制结构
10.1 选择结构
if
语句用于根据条件执行不同的代码块。
if 条件:
语句块
else:
语句块
10.2 多分支结构
当有多个条件需要判断时,可以使用 if - elif - else
结构。
if 条件:
语句块
elif 条件:
语句块
...
else:
语句块
10.3 嵌套
可以在 if
、elif
或 else
子句中嵌套其他的条件判断结构,以实现更复杂的逻辑。
10.4 三元运算符
<表达式 1> if <条件> else <表达式 2>
是一种简洁的条件表达式,根据条件的真假返回不同的值。
10.5 循环
while
循环:在指定条件为真时,重复执行循环体中的语句。
while 条件:
语句块
for
循环:用于遍历序列(如列表、元组、字符串等)中的元素。
for 元素 in 序列:
语句块
break
用于跳出循环,continue
用于跳过当前循环的剩余部分,直接开始下一次循环。
else
子句在循环正常结束(不是通过 break
跳出)时执行。
10.6 异常处理
try - except - (else) - (finally)
结构用于处理程序运行时可能出现的异常。
try:
可能引发异常的代码
except 异常类型 1:
处理异常类型 1 的代码
except 异常类型 2:
处理异常类型 2 的代码
...
else:
没有发生异常时执行的代码
finally:
无论是否发生异常都会执行的代码
# 选择结构
num = 5
if num > 3:
print("数字大于 3")
else:
print("数字小于等于 3")
# 多分支结构
grade = 85
if grade >= 90:
print("优秀")
elif grade >= 80:
print("良好")
elif grade >= 70:
print("中等")
elif grade >= 60:
print("及格")
else:
print("不及格")
# 嵌套
num = 10
if num > 5:
if num < 15:
print("数字在 5 和 15 之间")
# 三元运算符
result = "大于 5" if num > 5 else "小于等于 5"
print(result)
# 循环
# While 循环
count = 0
while count < 5:
print(count)
count += 1
# For 循环
for i in range(5):
print(i)
# Break、continue、else
for i in range(10):
if i == 5:
break # 跳出循环
elif i == 3:
continue # 跳过本次循环
print(i)
else:
print("循环正常结束")
# 异常处理
try:
num = 10 / 0
except ZeroDivisionError:
print("除数不能为 0")
else:
print("没有异常发生")
finally:
print("无论是否有异常,都会执行这里")