Python 基础(一)

🍦 Python由荷兰数学和计算机科学研究学会的Guido van Rossum于1990年代初设计,1991年发布,是跨平台解释型脚本语言。

1 语法

  • 缩进
    • 缩进指的是代码行开头的空格,便于阅读,非常重要。
    • 使用缩进表示代码块时,如果跳过缩进,运行将会返回一个错误。
    • 空格数量由程序员决定,最常见的是Tab四个空格或者两个空格。
    • 同个代码块中必须使用相同数量的空格缩进,否则返回一个错误。
1
2
if 7 > 3:
print("7 > 3") # 使用tab四个空格的缩进
  • 注释
    • 单行注释:以#开头。
    • 多行注释:以"""'''开头,以"""'''结尾,必须首尾成对。
1
2
3
4
5
6
7
print("This is a comment.")                 # 单行注释

""" # 多行注释
《劝学》· 孟郊
击石乃有火,不击元无烟。人学始知道,不学非自然。
万事须己运,他得非我贤。青春须早为,岂能长少年。
"""

2 变量

  • 变量
    • 存储数据值的容器,赋值时创建,Python没有用于声明变量的命令。
    • 变量不需要以任何特定类型进行声明,甚至可以在设置后更改类型,通过强制转换更改。
    • 使用函数type()获取变量的数据类型,使用单引号' '或双引号" "声明字符串变量。
1
2
3
4
5
6
7
8
9
x = 1                                       # 变量x设为int类型
x = "A" # 变量x更改为str类型
print(x)

y = int(3.5) # 强制转换变量y为int类型
print(y)

z = "A"
print(type(z)) # 获取变量z的数据类型

2-1 变量名

  • 变量名
    • 命名规则
      • 区分大小写(age、Age和AGE是不同的变量)。
      • 必须以字母或下划线开头,不能以数字开头。
      • 只能包含字母数字字符和下划线(Az、0-9和_)。
    • 命名方法
      • 蛇形命名法,每个单词都以下划线字符(_)分隔。
      • 小驼峰命名法,除首单词字母小写,其余单词都以大写字母开头。
      • 大驼峰命名法,又叫帕斯卡命名法,每个单词都以大写字母开头。
1
2
3
4
5
6
7
8
9
myname__ = "A"
my_name_ = "B"
_my_name = "C"
my__Name = "D"
__MyName = "E"

variable_name = "F" # 蛇形命名
variableNames = "G" # 小驼峰命名
VariableNames = "H" # 大驼峰命名

2-2 多值分配

  • 多值分配
    • 允许在一行中为多个变量赋值,也可在一行中为多个变量分配相同值。
    • 如果有一组列表或者元组,允许将值提取到变量中,该方法称为拆包。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
x, y, z = "Apple", "Grape", "Peach"        # 多个变量赋值
print(x)
print(y)
print(z)
print("-----")

x = y = z = "Lemon" # 多个变量分配相同值
print(x)
print(y)
print(z)
print("-----")

fruits = ["Apple", "Grape", "Peach"]
x, y, z = fruits # 拆包
print(x)
print(y)
print(z)

2-3 输出变量

  • 输出变量
    • 使用函数print()输出多个变量,逗号分隔,支持不同数据类型。
    • 使用+运算符输出多个变量,对于数字,该字符用于数学运算符。
    • 如果尝试使用+操作符组合字符串和数字,那么将TypeError报错。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
x = "Apple"
y = "Grape"
z = "Peach"
print(x, y, z)
print(x + " " + y + " " + z)

x = 2 # int类型
y = 1
print(x + y) # 2 + 1 = 3

x = "2" # str类型
y = "1"
print(x + y) # str(2) + str(1) = 21

x = 1
y = "A"
# print(x + y)
# TypeError: unsupported operand type(s) for +: 'int' and 'str'.

2-4 全局变量

  • 全局变量
    • 函数外创建的变量,每个人都可用,无论是函数内部或外部。
    • 函数内创建的同名变量,是局部变量,只能在函数内部使用。
    • 若函数内外创建同名变量,全局变量将保持原样,全局并具原始值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
x = "scripting language."                  # 在函数外部创建变量x,并在函数内部使用


def func_one():
print("Python is a " + x)


func_one()
y = "interpret language." # 在函数内部创建变量y,与全局变量y同名


def func_two():
y = "scripting language."
print("Python is a " + y)


func_two()
print("Python is a " + y)

2-5 全局关键字

  • 全局关键字
    • 在函数内部创建全局变量,使用global关键字。
    • 若更改函数内的全局变量,需要使用关键字引用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def func_one():                            # 使用global关键字,则变量x属于全局范围
global x
x = "scripting language."


func_one()
print("Python is a " + x)
y = "scripting language." # 更改函数内的全局变量值,使用global引用该变量


def func_two():
global y
y = "interpret language."


func_two()
print("Python is a " + y)

3 运算符

  • 运算符
    • 算术:+-*/%**//
    • 赋值:=+=-=*=/=%=**=//=&=|=^=>>=<<=
    • 比较:==!=><>=<=
    • 逻辑:andornot
    • 身份:isis not
    • 成员:innot in
    • 位运算:&|^~<<>>

3-1 算术

1
2
3
4
5
6
7
8
9
10
a, b = 3, 2

print(" a + b = ", a + b)
print(" a - b = ", a - b)
print(" a * b = ", a * b)
print(" a / b = ", a / b)
print(" a % b = ", a % b)
print(" a ** b = ", a ** b)
print(" a // b = ", a // b) # 向下取整除
print("-a // b = ", -a // b)

3-2 赋值

1
2
3
4
5
6
7
8
9
10
a, b = 3, 2

b += a # b = b + a
print(b)

b -= a # b = b - a
print(b)

b *= a # b = b * a
print(b)

3-3 比较

1
2
3
4
5
6
a, b = 3, 2

if a > b:
print("a > b")
else:
print("a < b")

3-4 逻辑

1
2
3
4
5
6
a, b = 3, 2

if a and b:
print("a和b两个都为True.")
else:
print("a和b有个不为True.")

3-5 身份

1
2
3
4
5
6
a, b = 3, 2

if a is b:
print("a和b有相同的标识.")
else:
print("a和b没有相同标识.")

3-6 成员

1
2
3
4
5
6
7
a, b = 3, 2
num_list = [1, 3, 5, 7, 9]

if a in num_list:
print("变量a在给定的列表num_list中.")
else:
print("变量a不在给定列表num_list中.")

3-7 位运算

1
2
3
4
a = 3
c = a << 2 # 3=0000 0011

print(c) # 左移两位,0000 1100=12

4 数据类型

  • 数据类型
    • 无类型:NoneType
    • 数字类型:intfloatcomplex
    • 文本类型:str
    • 布尔类型:bool
    • 序列类型:listtuplerange
    • 集合类型:setfrozenset
    • 映射类型:dict
    • 二进制类型:bytesbytearraymemoryview
1
2
3
4
5
6
7
8
x = 1
print(type(x)) # 打印变量x的数据类型

y = ["Apple", "Grape", "Peach"] # 设置数据类型
print(type(y))

z = dict(name="Lydia", age=24) # 使用构造函数设置特定的数据类型
print(type(z))

4-1 数字

  • 数字
    • int:整数,正数或负数,没有小数,长度不受限制。
    • float:浮点数,包含一个或多个小数的正数或负数,可有带e的科学数字表10的幂。
    • complex:复数,使用j作为虚部,可用complex(a, b)表示,也可用a + bj表示。
1
2
3
4
5
6
7
8
9
10
11
12
13
x = -1                                     # int
print(type(x))

y = 12E4 # float,12*10000
print(type(y))

z = 3 + 5j # complex,也可表示为complex(3, 5)
print(type(z))


import random # 使用random内置模块,用于生成随机数

print("<生成的随机数:" + str(random.randrange(1000, 10000)) + ">")
  • 构造:类型转换就是使用构造函数完成的。
    • int():整数、浮点数或字符串构造整数。
    • str():各种数据类型都可以构造字符串。
    • float():整数、浮点数或字符串构造浮点数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
x = -1                                     # int
y = 12E4 # float,12*10000
z = 3 + 5j # complex,也可表示为complex(3, 5)

a = float(x) # int转float
print(a)

b = int(y) # float转int
print(b)

# c = int(z) # 注意,这里不能将复数转换成其他数字类型,否则报错
# print(c) # TypeError: can't convert complex to float(int).

d = complex(x) # int转complex
print(d)

4-2 字符串

  • 字符串
    • Python中的字符串用单引号''或双引号""括起来。
    • 可以使用三个引号''''''将多行字符串分配给变量。
    • 字符串是表示Unicode字符的字节数组,没有char字符数据类型,单个字符只是长度为1的字符串。
    • 方括号可以用来访问字符串中的元素,由于字符串是数组,可以通过for循环遍历字符串中的字符。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
s = '''
不飞则已,一飞冲天。
不鸣则已,一鸣惊人。
'''
print(s) # 换行符插入到与代码相同的位置

a = "Apple"
print(a[0]) # 获取位置0的字符,即第一个字符的位置

for b in "Grape":
print(b) # for循环遍历单词Grape中的字母

c = "Hi!"
print(len(c)) # 使用len()函数获取字符串的长度

txt = "The best things in life are free!"
print("free" in txt) # 关键字in,检查txt文本中是否存在单词free
if "free" in txt:
print("存在于文本中")

print("expensive" not in txt) # 关键字not in,检查txt文本中是否不存在单词expensive
if "expensive" not in txt:
print("不存在文本中")

(1) 切片

  • 使用切片语法返回一系列字符。
  • 指定以冒号:分隔的开始和结束索引,返回字符串的一部分。
  • 通过省略开始索引,切片范围会从第一个字符开始,即位置0。
  • 通过省略结束索引,切片范围将到达末尾,也可以使用负索引从字符串末尾开始切片。
1
2
3
4
5
6
a = "Hello, World!"                         # 第1个字符H的索引位置是0

print(a[2: 5]) # 获取位置2到5的字符,不包括5
print(a[: 3]) # 获取位置0到3的字符,不包括3
print(a[10:]) # 获取位置10到最后的字符,包括10
print(a[-5: -2]) # 负索引:末尾字符!的索引位置是0,往左依次是-1,-2...

(2) 格式化

  • 使用+运算符连接或组合两个字符串,如果用于连接字符串和数字,将报错。
  • format()方法接受传递的参数,格式化字符串,可以用来组合字符串和数字。
    • 该方法接受无限数量的参数,并放置在相应的占位符中。
    • 可通过索引号{num}确保将参数放置在正确的占位符中。
    • 使用命名索引{name},传递参数值时必须使用相应的变量名name
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
x = "Hello "
y = "World."
z = x + y # 使用+运算符连接
print(z)

age = 24
txt = "My name is Lydia, and I am {} years old."
print(txt.format(age)) # 使用format()格式化方法

quantity = 3
items_no = 567
price_li = 49.95
order = "I want to pay {} dollars for {} pieces of item {}."
print(order.format(quantity, items_no, price_li))
order = "I want to pay {2} dollars for {0} pieces of item {1}."
print(order.format(quantity, items_no, price_li))

price = 49
txt = "The price is {:.6f} dollars."
print(txt.format(price)) # 将价格格式化为带六位小数的数字

order = "I have a {carname}, it is a {model}."
print(order.format(carname="Ford", model="Mustang"))

(3) 内置方法

  • upper():以大写形式返回字符串。
  • lower():以小写形式返回字符串。
  • strip():删除开头或结尾的任何空格。
  • replace():用另一个字符串替换当前字符串。
  • split():返回一个列表,其中指定分隔符之间的文本成为列表项。
1
2
3
4
5
6
7
a = " Hello, World!"

print(a.upper()) # 大写形式
print(a.lower()) # 小写形式
print(a.strip()) # 删除空格
print(a.replace("H", "J")) # 用J替换H
print(a.split(",")) # 使用逗号分隔符拆分字符串

(4) 转义字符

  • 想在字符串中插入非法字符,可以使用转义字符\,后跟插入的非法字符即可。
  • 常见的转义字符
    • \'(单引号)、\\(反斜杠)、\a(响铃)、\n(换行)、\r(回车)、\ooo(八进制)。
    • \v(纵向制表符)、\t(横向制表符)、\b(退格符)、\f(换页符)、\xhh(十六进制)。
1
2
3
txt = "We are the so-called \"Vikings\" from the north."

print(txt) # 转义双引号

4-3 布尔值

  • 布尔值
    • 只表示为TrueFalse,这两个值中的其中一个。
    • 函数bool()允许评估任何值并返回TrueFalse
1
2
3
4
5
6
7
8
9
a = 26
b = 30
if b > a:
print("b > a")
else:
print("b < a")

print(bool(135)) # 评估一个数字
print(bool("A")) # 评估一个字符串

(1) True值

  • 任何数字都是True,0除外。
  • 任何字符串都是True,空字符串除外。
  • 任何列表、元组、集合和字典都是True,空值除外。
1
2
3
print(bool(13579))
print(bool("abc"))
print(bool([1, 2, 3]))

(2) False值

  • 空值,例如[](){}""、数字0None,还有False本身。
  • 用户自定义类型的对象
    • 如果类定义了__len__()方法,并返回0或False,则输出False值。
    • 如果类同时定义__len__()__bool__()方法,则输出参考__bool__()的返回值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
print(bool(0))
print(bool(None))
print(bool(False))


class MyClassA():
def __len__(self):
return 0


print(bool(MyClassA())) # 定义了__len__()方法,并返回0


class MyClassB:
def __len__(self):
print("B.__len__()")
return 0

def __bool__(self):
print("B.__bool__()")
return True


if __name__ == "__main__":
print("True" if MyClassB() else "False")
print(bool(MyClassB())) # 同时定义了__len__()和__bool__()方法

(3) 返回情况

  • 创建返回布尔值的函数,可返回布尔值。
  • 返回布尔值的内置函数:isinstance()
1
2
3
4
5
6
7
8
def my_fun():
return True


print(my_fun()) # 创建返回布尔值的函数

x = 24
print(isinstance(x, int)) # 检查对象是否为int整数

4-4 列表

  • 列表
    • 用于将多个项目存储在单个变量中,使用方括号[]来创建。
    • 列表项是有序可变的,且允许重复值,索引时第一项为[0]
    • 列表长度使用len()函数计算,列表项可以是任何数据类型。
    • 列表的数据类型为<class 'list'>,使用list()构造函数创建新列表。
    • 四种集合数据类型
      • list:列表,有序且可变的集合,允许重复成员。
      • tuple:元组,有序不可变的集合,允许重复成员。
      • set:集合,无序且不可变的集合(可删除或添加元素),无索引,不允许重复成员。
      • dict:字典,有序且可变的集合(3.7版本开始有序,之前无序),不允许重复成员。
1
2
3
4
5
6
7
8
9
10
mylist = ["Apple", "Grape"]

print(len(mylist)) # 获取列表长度
print(type(mylist)) # 查看列表的数据类型

list1 = [1, 3, 5, 7, 9] # 列表项可以是整数、布尔数据等类型
list2 = [True, False, False]
list3 = ["abc", 123, True, "ABC"]
list4 = list(("a", "b", "c")) # list()函数创建新列表
print(list4)

(1) 访问表项

  • 通过索引号来访问列表项,第一项的索引为0。
  • 负索引从末尾开始,最后一项是-1,倒数第二项是-2,以此类推。
  • 指定开始和结束位置来指定索引范围,返回值将是包含指定项目的新列表。
  • 省略起始值,范围将从第一项开始,省略结束值,范围将继续到列表末尾。
  • 从列表末尾开始索引需指定负索引,使用in关键字确定列表中是否存在指定项。
1
2
3
4
5
6
7
8
9
10
mylist = ["Apple", "Grape", "Peach"]
print(mylist[1]) # Grape
print(mylist[-1]) # 负索引最后一项Peach
print(mylist[0: 2]) # 范围从0开始,到2结束,不包括2
print(mylist[: 2]) # 省略起始值,范围从0到2,不包括2
print(mylist[1:]) # 省略结束值,范围从1到末尾结束位置
print(mylist[-2: -1]) # 范围从-1到-2,不包括-1,即Grape

if "Apple" in mylist: # 确定mylist列表中是否存在指定项Apple
print("Yes, 'Apple' is in the fruits list.")

(2) 更改表项

  • 更改特定项目的值,需要参考索引号。
  • 更改特定范围内项目的值
    • 使用新值定义一个列表,并参考要插入新值的索引号范围。
    • 插入的项目多于替换的项目,则新项目将插入指定的位置,其余项目将相应移动。
    • 插入的项目少于替换的项目,则新项目将插入指定的位置,其余项目将相应移动。
    • 当插入的项目数和替换的项目数不匹配时,列表的长度会发生改变。
1
2
3
4
5
6
7
8
9
mylist = ["Apple", "Grape", "Peach"]
mylist[1] = "Lemon" # 更改项目值
print(mylist)

mylist[1: 2] = ["Mango", "Olive"] # 更改项目值范围,插入的项目多于替换的项目
print(mylist)

mylist[1: 3] = ["Grape"] # 插入的项目少于替换的项目,将第2和第3个值替换为1个值
print(mylist)

(3) 添加表项

  • append():将项目添加到列表的末尾。
  • insert():在指定索引处插入列表项。
  • extend()
    • 将另一个列表中的元素附加到当前列表,元素会被添加到列表的末尾。
    • 附加列表非必须,还可添加任何可迭代对象,例如元组、集合或字典。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
mylist = ["Apple", "Grape", "Peach"]
mylist.append("Lemon") # 将Lemon添加到列表末尾
print(mylist)

mylist.insert(1, "Mango") # 插入Mango作为第二项
print(mylist)

tropical = ["Mango", "Olive"]
mylist.extend(tropical) # 添加tropical元素到mylist列表
print(mylist)

mytuple = ("Apple", "Olive")
mylist.extend(mytuple) # 添加元组的元素到mylist列表中
print(mylist)

(4) 删除表项

  • remove():删除指定的项目。
  • pop():删除指定的索引,若不指定索引,则删除最后一项。
  • 使用del关键字可以删除指定的索引,也可以完全删除列表。
  • clear():清空列表,该列表仍然存在,但列表中没有内容。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
mylist = ["Apple", "Grape", "Peach", "Lemon", "Mango", "Olive"]
mylist.remove("Grape") # 删除Grape
print(mylist)

mylist.pop(1) # 删除第二项
print(mylist)

mylist.pop() # 删除最后一项
print(mylist)

del mylist[0] # 删除第一项
print(mylist)
del mylist # 删除整个列表,mylist此时不存在了

mylist = ["Apple", "Grape"]
mylist.clear() # 清除列表内容
print(mylist)

(5) 遍历表项

  • 使用for循环可以遍历列表项。
  • 还可以通过引用索引号遍历列表项,使用range()len()函数创建合适的迭代器。
  • 使用while循环遍历列表项,len()函数确定列表的长度,从0开始通过索引循环遍历。
  • 还可以使用列表推导式(List Comprehension)进行循环遍历。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
mylist = ["Apple", "Grape", "Peach"]

for x in mylist: # for循环遍历
print(x)
print("-----")

for y in range(len(mylist)):
print(mylist[y]) # 索引号遍历
print("-----")

z = 0
while z < len(mylist): # while循环遍历
print(mylist[z])
z = z + 1
print("-----")

[print(i) for i in mylist] # 列表推导式循环遍历

(6) 列表推导

  • 语法:newlist = [expression for item in iterable if condition == True]
  • 返回值是一个新列表,保持旧列表不变。
  • condition:条件是过滤器,只接受条件为True的项,可选项,可省略。
  • iterable:迭代对象可以是任何可迭代对象,例如列表、元组或集合等。
  • expression:表达式是迭代中的当前项,但也是结果,可作为操纵结果的方式包含条件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fruits = ["Apple", "Grape", "Peach"]

mylist = [x for x in fruits if x != "Apple"]
print(mylist) # 只接受条件不是Apple的物品

mylist = [x for x in fruits] # 条件可选
print(mylist)

mylist = [x for x in range(9)] # range()函数创建一个可迭代对象
print(mylist)

mylist = [x for x in range(20) if x < 9] # 加了“只接受小于9”的判断条件
print(mylist)

mylist = [x.upper() for x in fruits] # 将新列表中的值设置为大写
print(mylist)

mylist = [x if x != "Grape" else "Lemon" for x in fruits]
print(mylist) # 将Grape替换为Lemon

(7) 表值排序

  • sort()
    • 按字母数字顺序对列表进行排序,默认情况下升序。
    • 如果是降序排序,使用关键字参数reverse = True
    • 还可以使用关键字参数key = function自定义函数。
    • 默认情况下该方法区分大小写,所有大写字母排在小写字母之前。
    • 如果想要一个不区分大小写的排序,使用str.lower作为键函数。
  • reverse():反转元素的当前排序顺序。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
mylist = ["Lemon", "Mango", "Apple", "Olive", "Grape"]
mylist.sort() # 升序,从小到大
print(mylist)
mylist.sort(reverse=True) # 降序,从大到小
print(mylist)


def func(n):
return abs(n - 50) # 根据数字与50的接近程度对列表进行排序


mylist = [100, 50, 65, 82, 23, 56, 73, 14, 1]
mylist.sort(key=func) # 返回一个用于对列表进行升序排序的数字
print(mylist)

mylist = ["lemon", "apple", "olive", "grape"]
mylist.sort() # 区分大小写,大写在前,小写在后
print(mylist)
mylist.sort(key=str.lower) # 不区分大小写的排序
print(mylist)

mylist = ["lemon", "apple", "olive", "grape"]
mylist.reverse() # 颠倒列表项的顺序
print(mylist)

(8) 其他操作

  • 列表复制:copy()制作列表副本,list()制作列表副本的另一种方法。
  • 列表添加
    • 可以使用+运算符可以连接两个或多个列表。
    • 将另一列表中的所有项目逐个附加到一列表中。
    • 通过extend()方法将一个列表中的元素添加到另一个列表中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
mylist = ["Apple", "Grape", "Peach"]
cplist1 = mylist.copy() # 使用copy()方法复制
print(cplist1)
cplist2 = list(mylist) # 使用list()方法复制
print(cplist2)

list1 = ["a", "b", "c"]
list2 = [1, 2, 3, 4]
list3 = list1 + list2 # +运算符
print(list3)

for x in list2:
list1.append(x) # 逐个符加到list1列表中
print(list1)

list1 = ["a", "b", "c"]
list2 = [1, 2, 3, 4]
list1.extend(list2) # extend()方法在list1列表末尾添加list2元素
print(list1)

(9) 内置方法

  • count():统计列表元素出现的次数。
  • index():返回指定值首次出现的位置。
1
2
3
4
mylist = ["Apple", "Grape", "Peach", "Apple", "Apple"]

print(mylist.count("Apple")) # 统计Apple出现的次数
print(mylist.index("Peach")) # 返回Peach首次出现的位置

4-5 元组

  • 元组
    • 用在单个变量中存储多个项目,用圆括号()书写。
    • 元组项是有序不可更改的,并且允许重复值,被索引时第一项索引为[0]
    • len()函数确定元组长度,创建一个只有一项的元组,须在项目后添加一个逗号。
    • 元组项可以是任何数据类型,例如字符串、整数或布尔类型等,可以包含不同类型。
    • 元组的数据类型为<class 'tuple'>,可使用tuple()构造函数创建一个新的元组。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
mytuple = ("Apple", "Grape", "Peach", "Apple", "Mango")
print(len(mytuple)) # 打印元组中的项目数

mytuple = ("Apple", ) # 一项元组,必须在项目后添加一个逗号
print(type(mytuple)) # <class 'tuple'>

mytuple = ("Apple", "Grape") # 圆括号书写
print(mytuple)

mytuple = ("Apple", "Apple") # 允许重复值
print(mytuple)

tuple1 = ("a", "b", "c") # 字符串类型
tuple2 = (1, 3, 5, 7, 9) # 整数类型
tuple3 = (True, 24, "s") # 包含不同类型

mytuple = tuple(("Apple", "Grape")) # tuple()函数创建新元组
print(mytuple)

(1) 访问组值

  • 通过引用方括号内的索引号来访问元组项,第一项的索引为0。
  • 负索引从末尾开始,最后一项是-1,倒数第二项是-2,以此类推。
  • 指定开始和结束位置来指定索引范围,返回值将是具有指定项目的新元组。
  • 省略起始值,范围将从第一项开始,省略结束值,范围将继续到列表末尾。
  • 从元组末尾开始索引需指定负索引,使用in关键字确定元组中是否存在指定项。
1
2
3
4
5
6
7
8
9
10
11
12
mytuple = ("Apple", "Grape", "Peach")
print(mytuple[1]) # Grape
print(mytuple[-1]) # 打印元组的最后一项Peach

mytuple = ("Apple", "Grape", "Peach", "Mango", "Lemon", "Melon", "Olive")
print(mytuple[2: 5]) # 返回第3、4、5项
print(mytuple[: 3]) # 省略起始值,范围从0到3,不包括3
print(mytuple[4:]) # 省略结束值,范围从4到末尾结束位置
print(mytuple[-4:-1]) # 返回从索引-4到索引-1,不包括-4的项目

if "Apple" in mytuple: # 确定mytuple元组中是否存在指定项Apple
print("Yes, 'Apple' is in the fruits tuple.")

(2) 更新组值

  • 元组一旦创建就不可更改,可将其转换为列表,更改列表再转换回元组。
  • 若要添加一个或多个项目,使用这些项目创建一个新元组,并将其添加到现有元组中。
  • 删除元组中的项目同样需要先转换为列表进行操作,del关键字则可以完全删除元组。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
mytuple = ("Apple", "Grape", "Peach")
mylists = list(mytuple) # 将元组转换为列表
mylists[1] = "Mango" # 更改列表
mytuple = tuple(mylists) # 再将列表转换回元组
print(mytuple)

newtuple = ("Lemon", ) # 创建新元组
mytuple += newtuple # 添加该元组
print(mytuple)

mylists = list(mytuple) # 转换为列表
mylists.remove("Apple") # 删除列表项
mytuple = tuple(mylists) # 转换回元组
print(mytuple)

del mytuple # 完全删除元组
# print(mytuple) # NameError: name 'mytuple' is not defined.

(3) 元组拆包

  • 创建元组并赋值称为元组打包,将值提取回变量中则称为元组拆包。
  • 拆包时变量数须与元组值的数量匹配,否则使用星号*将剩余值收集为列表。
  • 若星号被添加到另一变量而非最后一个,Python将为变量分配值,直至剩余值数量与剩余变量数匹配。
1
2
3
4
5
6
7
8
9
10
mytuple = ("Apple", "Grape", "Peach")
(green, yellow, red) = mytuple # 元组拆包
print(green)

mytuple = ("Apple", "Grape", "Peach", "Mango", "Lemon")
(green, yellow, *red) = mytuple # 使用星号*将剩余值收集为列表
print(red)

(green, *tropic, red) = mytuple # 添加tropic变量值列表
print(tropic)

(4) 元组循环

  • 使用for循环可以遍历元组项。
  • 还可以通过引用索引号遍历元组项,使用range()len()函数创建合适的迭代器。
  • 使用while循环遍历元组项,len()函数确定元组的长度,从0开始通过索引循环遍历。
1
2
3
4
5
6
7
8
9
10
11
12
13
mytuple = ("Apple", "Grape", "Peach")
for x in mytuple: # for循环遍历
print(x)
print("-----")

for y in range(len(mytuple)):
print(mytuple[y]) # 索引号遍历
print("-----")

z = 0
while z < len(mytuple): # while循环遍历
print(mytuple[z])
z = z + 1

(5) 添加元组

  • 使用+运算符可以连接两个或多个元组。
  • 使用*运算符将元组内容乘以给定次数。
1
2
3
4
5
6
7
8
tuple1 = ("a", "b", "c")
tuple2 = (0, 1, 2, 3, 4, 5, 6)
tuple3 = tuple1 + tuple2
print(tuple3) # +运算符

fruits = ("Apple", "Grape")
mytuple = fruits * 2 # *运算符
print(mytuple)

(6) 内置方法

  • count():统计元组中元素出现的次数。
  • index():返回指定值首次出现的位置。
1
2
3
4
mytuple = ("Apple", "Grape", "Peach", "Apple")

print(mytuple.count("Apple")) # 统计Apple出现的次数
print(mytuple.index("Grape")) # 返回Grape首次出现的位置

4-6 集合

  • 集合
    • 用于将多个项目存储在单个变量中,用大括号{}书写。
    • 集合项是无序不可更改的,且无索引,也不允许重复值。
    • len()函数确定集合长度,集合项可以是任何数据类型。
    • 例如字符串、整数或布尔类型等,可以包含不同数据类型。
    • 集合的数据类型为<class 'set'>,使用set()构造函数创建一个新集合,for循环遍历集合项。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
myset = {"Apple", "Grape"}
print(len(myset)) # 获取集合中的项目数
for x in myset: # for循环遍历
print(x)

print(type(myset)) # <class 'set'>
print(myset) # 大括号书写

myset = {"Apple", "Grape", "Apple"}
print(myset) # 不允许重复值

set1 = {"a", "b", "c"} # 字符串类型
set2 = {1, 3, 5, 7, 9} # 整数类型
set3 = {True, 26, "s"} # 包含不同类型

myset = set(("Apple", "Grape"))
print(myset) # set()函数创建新集合

(1) 访问集合项

  • 不能通过索引访问集合项,使用for循环遍历,或使用in关键字确定集合中是否存在指定值。
1
2
3
4
5
6
myset = {"Apple", "Grape", "Peach"}
for x in myset: # for循环遍历
print(x)

print("-----")
print("Banana" in myset) # in关键字确定

(2) 添加集合项

  • 创建集合后无法更改集合项,但add()方法可添加新项目。
  • 使用update()方法可以将另一个集合项添加到当前集合中。
  • update()方法中的对象,可以是任何可迭代的对象,例如元组、列表或字典等。
1
2
3
4
5
6
7
8
9
10
11
myset = {"Apple", }
myset.add("Grape") # add()方法添加集合项
print(myset)

tropical = {"Mango", }
myset.update(tropical) # 添加tropical集合项到myset
print(myset)

mylist = ["Peach", ]
myset.update(mylist) # 添加列表元素到myset集合中
print(myset)

(3) 删除集合项

  • 使用remove()discard()方法删除集合中的项目。
    • 如果要删除的集合项不存在,使用remove()将会报错。
    • 如果要删除的集合项不存在,使用discard()不会报错。
  • pop()方法删除最后一项,集合无序,不确定删除的具体项。
  • clear()方法清空集合,集合仍在,del关键字完全删除集合。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
myset = {"Apple", "Grape", "Peach"}
myset.remove("Grape") # remove()方法删除Grape
print(myset)

# myset.remove("Grape") # 不存在集合项,报错KeyError: 'Grape'.
myset.discard("Grape") # 不存在集合项,使用discard()方法不会报错
print(myset)

thisset = myset.pop() # 删除最后一项
print(myset)
print(thisset)

myset = {"Apple", "Grape", "Peach"}
myset.clear() # 清空集合
print(myset)

del myset # 完全删除集合
# print(myset) # NameError: name 'myset' is not defined.

(4) 集合运算

  • union():返回一个包含两个集合中所有项目的新集合,会排除重复项。
  • update():将一个集合的所有项目插入到另一个集合中,会排除重复项。
  • intersection():仅包含存在于两个集合中的相同项。
  • intersection_update():仅保留两个集合中存在的相同项。
  • symmetric_difference():仅包含存在于两个集合中的不同项。
  • symmetric_difference_update():仅保留两个集合中存在的不同项。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
set1 = {"a", "b"}
set2 = {1, "b"}
set3 = set1.union(set2) # 返回一个新集合set3
print(set3)
set1.update(set2) # 将set2中的所有项目插入到set1中
print(set1)

set1 = {"a", "b", 1}
set2 = {1, 2, "a", "b", "c"}
set3 = set1.intersection(set2) # 仅包含存在于set1和set2中的相同项
print(set3)
set1.intersection_update(set2) # 仅保留set1和set2中存在的相同项
print(set1)

set1 = {"a", "b", "c"}
set2 = {1, 2, 3, "b", "c"}
set3 = set1.symmetric_difference(set2) # 仅包含存在于set1和set2中的不同项
print(set3)
set1.symmetric_difference_update(set2) # 仅保留set1和set2中存在的不同项
print(set1)

(5) 内置方法

  • copy():复制一个集合。
  • difference():返回集合的差集。
  • difference_update():移除指定集合中包含与另一个集合相同项的元素。
  • isdisjoint():判断两个集合是否相交,不相交返回True,否则返回False。
  • issubset():判断集合是否被其他集合包含,是则返回True,否则返回False。
  • issuperset():判断集合是否包含其他集合,是则返回True,否则返回False。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
set1 = {"a", "f"}
set2 = {1, 2, 3, "b", "c"}
set3 = set1.copy() # 复制set1
print(set3)
set3 = set1.difference(set2) # 差集
print(set3)
set1.difference_update(set2) # 移除set1中与set2相同的元素,返回set1中剩余的元素
print(set1)

set1 = {"a", "b", "f"}
set2 = {1, 2, 3, "b", "c"}
set3 = {1, 2, 3, "a", "b", "c"}
result = set1.isdisjoint(set2) # 判断是否相交,不相交为True
print(result)
result = set1.issubset(set3) # 判断set1是否被set3包含
print(result)
result = set1.issuperset(set2) # 判断set1是否包含set2
print(result)

4-7 字典

  • 字典
    • 用于将数据值存储在键值对中,使用大括号{}进行书写,带有键和值。
    • 字典项目是有序可更改且不允许重复的,键值对形式呈现,用键名引用。
    • 可使用len()函数获取字典长度,字典的数据类型为<class 'dict'>
    • 字典的值可以是任何数据类型,例如:字符串、整数、布尔值或列表等。
1
2
3
4
5
6
7
8
9
10
11
12
mydict = {
"brand": "Ford",
"model": "Mustang", # 字符串
"year": 1964, # 整数
"colors": ["red", "blue", "white"], # 列表
"colors": ["red", "blue"]
}

print(len(mydict)) # 打印字典中的项目数
print(mydict["brand"]) # 使用键名引用
print(type(mydict)) # <class 'dict'>
print(mydict) # 不允许重复,重复值将覆盖现有值

(1) 访问字典项

  • 通过引用方括号内的键名来访问字典的项目,还可以使用get()方法获取。
  • 修改原字典对象,视图对象的值也会发生改变,视图对象包括以下三个方法。
    • keys()方法返回字典中所有的键列表。
    • values()方法返回字典中所有的值列表。
    • items()方法以列表返回可遍历的元组数组。
  • 使用in关键字可以确定字典中是否存在指定的键。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
mydict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

print(mydict["model"]) # 引用键名访问
print(mydict.get("model")) # get()方法获取
print(mydict.keys()) # 获取键列表
mydict["colors"] = "white" # 修改原字典mydict的colors对象
print(mydict.keys()) # 获取的键列表也得到更新
print(mydict.values()) # 获取值列表
mydict["year"] = 2022 # 修改原字典mydict的year对象
print(mydict.values()) # 获取的值列表也得到更新
print(mydict.items()) # 返回字典中的每个项目作为列表的元组
mydict["year"] = 2020 # 修改原字典mydict的year对象
print(mydict.items()) # 获取的元组数组也得到更新

if "model" in mydict: # 检查mydict字典中是否存在model对象
print("Yes, 'model' is one of the keys in mydict dictionary.")

(2) 更改字典项

  • 通过引用键名来更改特定字典项的值。
  • update()方法使用给定参数中的字典项更新字典,参数必须是字典或具有键值对的可迭代对象。
1
2
3
4
5
6
7
8
9
10
mydict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

mydict["year"] = 2019 # 引用键名更改
print(mydict)
mydict.update({"year": 2021}) # update()方法更新
print(mydict)

(3) 添加字典项

  • 通过使用新的索引键并为其分配值来完成向字典添加项目。
  • update()方法使用给定参数中的字典项更新字典,参数必须是字典或具有键值对的可迭代对象。
1
2
3
4
5
6
7
8
9
10
mydict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

mydict["color"] = "red" # 使用新的索引键并为其分配值
print(mydict)
mydict.update({"price": 2000000}) # update()方法将price添加到字典中
print(mydict)

(4) 删除字典项

  • pop():删除具有指定键名的项目。
  • popitem():删除最后插入的项目,3.7之前的版本会删除随机项目。
  • 使用del关键字删除具有指定键名的项目,也可以完全删除整个字典。
  • clear():清空字典。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
mydict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"colors": "red",
"price": 20000000
}

mydict.pop("model") # 删除指定键名的项目
print(mydict)
mydict.popitem() # 删除最后插入的项目
print(mydict)
del mydict["brand"] # 删除指定键名的项目
print(mydict)
mydict.clear() # 清空字典
print(mydict)
del mydict # 完全删除整个字典
# print(mydict) # NameError: name 'mydict' is not defined.

(5) 遍历字典项

  • for循环可以遍历字典项,返回值可以是字典的键,也可以是字典的值。
  • 可以使用for循环配合keys()values()方法分别返回字典的键和值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
mydict = {
"A": "Apple",
"G": "Grape",
"P": "Peach"
}

for x in mydict:
print(x) # 打印字典中的所有键
print("-----")
for y in mydict:
print(mydict[y]) # 打印字典中的所有值
print("-----")
for a in mydict.keys():
print(a) # keys()方法返回键
print("-----")
for b in mydict.values():
print(b) # values()方法返回值
print("-----")
for x, y in mydict.items():
print(x, y) # items()方法遍历keys和values

(6) 字典复制

  • copy()方法可以复制副本,dict()方法则可以制作副本。
1
2
3
4
5
6
7
8
9
10
mydict = {
"A": "Apple",
"G": "Grape",
"P": "Peach"
}

dict1 = mydict.copy() # 复制副本
print(dict1)
dict2 = dict(mydict) # 制作副本
print(dict2)

(7) 字典嵌套

  • 字典嵌套指字典可以包含字典,可以将其他字典添加到一个新字典中。
1
2
3
4
5
6
7
8
9
10
11
12
13
myfamily = {                               # 创建一个包含两个字典的字典
"child1": {"name": "Emil", "year": 2010},
"child2": {"name": "Tobias", "year": 2020}
}
print(myfamily)

child1 = {"name": "Emil", "year": 2010}
child2 = {"name": "Tobias", "year": 2020}
myfamily = { # 创建一个包含两个字典的新字典
"child1": child1,
"child2": child2
}
print(myfamily)

(8) 内置方法

  • setdefault():与get()方法类似,如果键不存在于字典中,就会添加键并将值设为默认值。
  • fromkeys():创建新字典,以序列中的元素作为字典的键,value为字典所有键对应的初始值。
1
2
3
4
5
6
7
8
9
10
11
12
mydict = {"A": "Hi~", "G": "Grape"}
print(mydict.setdefault("A")) # 与get()方法类似
print(mydict.setdefault("A", None))
print(mydict.setdefault("P")) # 添加键并将值设为默认值None,默认为None后再设置则无效
# print(mydict.setdefault("P", "Peach"))
print(mydict)

seq = ("Apple", "Grape", "Peach")
mydict = dict.fromkeys(seq) # 不指定默认的键值,默认为None
print(str(mydict)) # {'Apple': None, 'Grape': None, 'Peach': None}
mydict = dict.fromkeys(seq, 1000) # 指定默认的键值为1000
print(str(mydict)) # {'Apple': 1000, 'Grape': 1000, 'Peach': 1000}

5 数组

  • 数组
    • Python没有数组类型,只有列表类型,数组可以用列表来替代。
    • 数组用于在一个变量中存储多个值,通过索引号来访问这些值。
    • Python没有对数组的内置支持,列表代替时内置方法与之相通。
      • append()clear()copy()count()extend()
      • index()insert()pop()remove()reverse()sort()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fruits = ["Apple", "Grape", "Peach"]
print(len(fruits)) # 返回该数组的长度,长度总比最高数组索引数大1
print(fruits[0]) # 获取第一个数组项的值
fruits[0] = "Lemon" # 修改第一个数组项的值

for x in fruits: # 使用for循环遍历数组的所有元素
print(x)

fruits.remove("Peach") # remove()方法从数组删除Peach元素,只删除第一次出现的指定值
print(fruits)

fruits = ["Apple", "Grape", "Peach"]
fruits.pop(1) # pop()方法从数组删除第二个元素
print(fruits)

fruits.append("Mango") # append()方法添加元素
print(fruits)

5-1 numpy库

  • numpy库
    • 数组在numpy库中定义,若要使用,需事先导入库,数组类型为<class 'numpy.ndarray'>
    • numpy中的数组对象称为ndarray,通过使用array()函数可以创建一个numpy的ndarray对象。
    • 将列表、元组或任何类似数组的对象传递给array()方法,array()方法将其转换为ndarray。
1
2
3
4
5
6
7
8
9
10
11
import numpy as np

myArray = np.array([[1, 2, 3, 7, 8, 9], [4, 5, 6, 0, 1, 2]])
print(myArray) # 列表创建数组
print(type(myArray)) # <class 'numpy.ndarray'>

myArray = np.array((
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
))
print(myArray) # 元组创建数组

5-2 数组维度

  • 数组维度
    • 数组维度是嵌套数组的一个级别,嵌套数组即数组中有数组。
    • 零维数组,也叫标量,数组值只有一个。
    • 一维数组,指由多个元素值构成的数组。
    • 二维数组
      • 是一维数组的数组,通常用于表示矩阵,或者是二阶张量。
      • numpy库中有专门用于矩阵运算的完整子模块numpy.mat
    • 三维数组,是二维数组的数组。
    • 数组可以拥有任意数量的维度,创建数组时使用ndmin参数定义维数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import numpy as np

a = 1
arr0 = np.array(a) # 零维数组
print(arr0)
print(arr0.ndim) # ndim属性返回一个整数,检查数组维度
print(arr0.shape) # 返回元组,获取数组各个维度的维数
print("-----")

b = [1, 2, 3]
arr1 = np.array(b) # 一维数组
print(arr1.ndim)
print(arr1.shape)
print(arr1)
print("-----")

c = [[1, 2], [4, 5]]
arr2 = np.array(c) # 二维数组
print(arr2.ndim)
print(arr2.shape)
print(arr2)
print("-----")

d = [[7, 8], [10, 11]]
arr3 = np.array([c, d]) # 三维数组
print(arr3)
print(arr3.shape)
print(arr3.ndim)
print("-----")

arr5 = np.array([1, 2, 3, 4], ndmin=5)
print(arr5.ndim) # 五维数组
print(arr5.shape)
print(arr5)

5-3 数组裁切

  • 数组裁切
    • 数组裁切类似列表和元组的切片,格式:[start: end][start: end: step]
    • 将元素从一个给定的索引切到另一个给定的索引,包含开始索引,不包含结束索引。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import numpy as np

arr1 = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr1.ndim) # 一维数组
print(arr1[1: 3]) # 裁切索引1到3的元素
print(arr1[1: 5: 2]) # 设置裁切步长为2
print(arr1[:: 4]) # 返回数组中相隔的元素
print(arr1[-3: -1]) # 负裁切,索引从-1开始
print("-----")

arr2 = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr2.ndim) # 二维数组
print(arr2[1, 1: 3]) # 第二个元素[6, 7, 8, 9, 10],索引号从1到3的元素
print(arr2[0: 2, 2]) # 第一个元素和第二个元素,各自索引号为2的元素
print(arr2[0: 2, 1: 3]) # 第一个元素和第二个元素,各自索引号从1到3的元素,返回数组

6 if语句

  • if语句
    • 使用if关键字编写。
    • 支持if...if...elif...if...elif...else...if...else...四种格式。
    • if...格式,如果只有一条语句要执行,可以将该条执行语句与if语句放在同一行上。
    • if...else...格式,如果只有一条语句要执行,可以将执行语句与if语句放在同一行。
    • 如果if语句没有内容输出,使用pass关键字可以避免语句报错。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
a = 10
b = 20
if b > a: # 注意缩进,若没有缩进,会报错
print("a < b")
elif a == b: # 如果if条件不成立,则执行elif
print("a = b")
else: # else关键字捕获任何未被上述条件捕获的内容
print("a > b")

if a < b: print("a < b") # 只有一条语句要执行,将执行语句与if语句放在同一行
print("B") if a < b else print("A") # 又叫三元运算符或条件表达式,还可同一行上多个else语句
print("A") if a > b else print("=") if a == b else print("B")

x = 23
if x > 10: # if嵌套
print("x > 10")
if x > 20:
print("x > 20")
else:
print("x < 20")

if a == b:
pass # pass关键字避免出错

7 for循环

  • for循环
    • 用于迭代序列,例如列表、元组、集合或字符串等,不需要预先设置索引变量。
    • 使用break关键字,可以在循环遍历所有项目之前停止循环。
    • continue关键字,停止循环的当前迭代,并继续下一个循环。
    • 若for循环语句没内容输出,使用pass关键字可避免语句报错。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
fruits = ["Apple", "Grape", "Peach"]
for x in fruits:
print(x) # 遍历列表
print("-----")

for y in "Grape":
print(y) # 遍历字符串
print("-----")

for z in fruits:
print(z) # Apple, Grape
if z == "Grape":
break # 遍历到Grape时break停止,跳出循环
print("-----")

for a in fruits:
if a == "Grape":
break
print(a) # Apple
print("-----")

for b in fruits:
if b == "Grape":
continue # 遍历到Grape时continue跳过,继续下一个循环
print(b) # Apple, Peach
print("-----")

obj = ["red", "big", "delicious"]
for a in obj: # for循环嵌套
for b in fruits:
print(a, b)

for c in [1, 2, 3]:
pass # pass关键字避免出错

7-1 range()函数

  • range()函数
    • 循环一组代码指定的次数,可以使用range()函数。
    • 返回一个数字序列,默认从0开始递增1,并以指定的数字结束。
    • range()函数默认是以0作为起始值的,通过添加参数来指定。
    • range()函数默认序列递增1,可以通过添加第3个参数来指定。
1
2
3
4
5
6
7
8
9
10
for a in range(3):
print(a) # 打印0到2的值,序列递增1
print("-")

for b in range(3, 6):
print(b) # 打印3到5的值,序列递增1
print("-")

for c in range(3, 10, 3):
print(c) # 打印3到9的值,序列递增3

7-2 else关键字

  • else关键字
    • for循环中的else关键字用来指定循环结束时要执行的代码块。
    • 如果循环语句被break停止,则else语句的代码块不会被执行。
1
2
3
4
5
6
7
8
9
10
for x in range(3):
print(x) # 打印从0到3的所有数字,并在循环结束时打印一条信息
else:
print("-")

for y in range(6):
if y == 1: break # 当循环到y为3时,break停止并跳出循环,else语句不执行
print(y)
else:
print("Finally finished!")

8 while循环

  • while循环
    • 只要条件为真,就可以执行一组语句。
    • 使用break关键字,即使while条件为真,也可以停止循环。
    • 使用continue关键字,停止当前迭代,并继续下一个循环。
    • 当条件不再为真时运行一段代码,可以使用else语句。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
a = 1
while a < 3:
print(a) # 打印小于3的数
a += 1 # 注意递增,否则循环永远继续
print("-")

b = 1
while b < 5:
print(b)
if b == 3:
break # 当b为3时break停止,跳出循环
b += 1
print("-")

c = 0
while c < 5:
c += 1
if c == 3:
continue # 当c为3时,继续下一次迭代
print(c)
print("-")

x = 1
while x < 6:
print(x)
x += 1
else: # 条件不再为真时运行
print("x >= 6")

Python 基础(一)
https://stitch-top.github.io/2021/01/01/python/python01-python-ji-chu-yi/
作者
Dr.626
发布于
2021年1月1日 23:33:10
许可协议