PY入门2

条件判断

if…elif…else…:满足条件时执行对应逻辑

1
2
3
4
5
6
7
8
9
10
11
12
admin_name='admin'
admin_password='123456'
while True:
username = input("Enter your username: ")
password = input("Enter your password: ")
if username == admin_name and password == admin_password:
print("Login Successful")
break
elif username == admin_name and password != admin_password:
print("Wrong Password")
else:
print("Wrong Username")

模式匹配

**match…case…**与switch…case一致,根据条件精准匹配

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
while True:
class_id = input('Please enter your class ID: ')
match class_id:
case "101":
print('Class ID: 101')
break
case "102":
print('Class ID: 102')
break
case "103":
print('Class ID: 103')
break
case _: #other match
print('Class ID Not Found')

循环

while…else…for ele in data…else…
while循环在上述中以使用,只不过条件一直设置为True,在实际情况中可以灵活设置,比如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
flag=True
while flag:
class_id = input('Please enter your class ID: ')
match class_id:
case "101":
print('Class ID: 101')
flag -= 1
case "102":
print('Class ID: 102')
flag -= 1
case "103":
print('Class ID: 103')
flag -= 1
case _: #other match
print('Class ID Not Found')
else:
print('Found Class ID')

for循环是一种轮询遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class_room=[]
class_num=101
for i in range(3):
class_room.append(class_num)
class_num+=1
class_id=input("Enter Class ID")
for i in class_room:
if i==int(class_id):
print("Class ID",class_id)
break
elif i==class_room[len(class_room)-1]:
print("Class ID Not Found")
else:
print('End')

嵌套循环
冒泡为例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
data_arr=[]
data=input('Please enter the number of rows: ')
now_data=''
for i in data:
if i!=',':
now_data+=i
else:
data_arr.append(int(now_data))
now_data=''
else:
if now_data:
data_arr.append(int(now_data))
for i in range(len(data_arr)):
for j in range(len(data_arr)-1-i):
if data_arr[j]>data_arr[j+1]:
data_arr[j],data_arr[j+1]=data_arr[j+1],data_arr[j]
print(data_arr)

数据容器

用来存储大量数据(列表list、字符串str、元组tuple、集合set、字典dict)

List

可以存储不同类型的元素,元素有序、可重复、可修改,可通过索引访问(0开始,反向索引从-1开始)
增删改查

1
2
3
4
list_type=[1,2,3,2]
del list_type[0]
list_type.append(3)
print(list_type)

切片列表、字符串、元组等:序列数据[开始索引:结束索引:步长],默认为[0,len(list),1]

1
2
list_type=[1,2,3,2,873,2,10,1,2,46,2,56]
print(list_type[2:9:2])# [3, 873, 10, 2]

常见方法
append(ele)、insert(index,ele)、remove(first_ele)、pop(index)、sort()、reverse()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
data_arr=[]
data=input('Please enter the number of rows: ')
now_data=''
for i in data:
if i!=',':
now_data+=i
elif now_data:
data_arr.append(int(now_data))
now_data=''
else:
if now_data:
data_arr.append(int(now_data))
data_arr.sort()
print(data_arr[0],data_arr[-1],sum(data_arr)/len(data_arr))

去重

1
2
3
4
5
6
7
8
9
list1=[0,1,12,34,5]
list2=[1,2,3,4,5]
list1=[*list1,*list2]# 解组包操作
list3=[]
for i in list1:
if i not in list3:
list3.append(i)
list3.sort()
print(list3)

Str

无法修改、有序、可迭代
具备索引,可通过索引查询
索引and切片应用与List一致
常用方法
find(str):返回匹配str的索引或-1
count(str):统计匹配次数
upper():转大写
lower():转小写
split(split_str):指定分割符为列表
strip(strip):去除空白字符或指定字符
replace(old,new): 替换子串
startswith(str)是否以指定子串开头,返回bool

Tuple

在某一些情景下,数据只能被查询而无法被修改时,我们可以用元组(tuple)来存储
重复、有序、不可修改(支持索引,切片)
定义单元素元组要在后面加,

1
2
3
4
5
6
t0=(1,2,5,3,21,78,2)
t1=() #tuple()
t3=(1,) #t3=(1)会被认为多余括号
t0[1] #2
t0.index(2) #1 获取第一个ele的索引
t0.count(2) #2

组、解包

1
2
3
t0=1,2,3 #t0=(1,2,3)
a,b,c=t0 #a=1,b=2,c=3,数目对应
x,*y=t0 #x=1,y=[2,3],会生成列表

Set

需要批量存储不可重复的数据(唯一标识),能够自动去重
无序、不重复、可修改

1
2
s1={1,2,3}
s2=set()#定义空集合,不可使用s2={},{}是空字典

使用组解包和集合特性进行快速去重

1
2
3
4
5
list1=[0,1,12,34,5]
list2=[1,2,3,4,5]
list1=[*{*list1,*list2}]
list1.sort()
print(list1)

常用方法
add(ele)、remove(ele)、pop()随机删除元素、clear()清空、difference(setData)差集、union(setData)并集、intersection(setData)交集

Dict

字典中存储键值对{key:value,…}
不重复、可修改

1
2
3
d1={} #d1=dict()
d2={'Jay':100,'John':90,'Bob':97}
d2['Jay'] # 100

常用操作

1
2
3
4
5
6
7
8
d0=dict()
d0['a'],d0['b']=10,20
d0.pop('a')
del d0['b']
d0['c'],d0['d']=30,30
d0['c']=20
print(d0.get('c'),d0.keys(),d0.values(),d0.items())
# 20 dict_keys(['c', 'd']) dict_values([20, 30]) dict_items([('c', 20), ('d', 30)])

PY入门2
http://example.com/2026/03/22/PY入门2/
作者
印星
发布于
2026年3月22日
许可协议