基础练习二


本章概述:python基础——基础练习二


1、题目及要求

制作简单的学生信息录入系统

要求

  • 增加学生信息
  • 查找学生信息
  • 删除学生信息
2、部分代码展示
2.1、增加学生信息函数

学生信息应包括学生学号、学生姓名、性别、年龄等。

增加学生信息这个函数的关键在于,学生信息用什么类型的数据来表示?由于这里不涉及持久化存储,所以我们不需要考虑存储到硬盘的方式。在这里我们可以使用字典来表示每个学生的信息,用学号来作为每个学生的key,key是唯一的,用学号刚好合适,因为每个学生的学号肯定是不同的。

1
2
3
4
5
6
7
8
9
10
11
12
def Add_students(ID,Name,Sex,Age):
if ID <= 0:
print('\n学号ID格式错误,学号必须为正整数\n即将回到选项页面\n')
return 0
if Sex not in ['男','女']:
print('\n性别Sex格式错误,性别只能输入男或者女\n即将回到选项页面\n')
return 0
if Age > 100:
print('\n年龄格式有误,年龄可输入范围在1-100之间\n即将回到选项页面\n')
return 0
Student_Dict[ID]={'姓名':Name,'性别':Sex,'年龄':Age}
return Student_Dict
2.2、查找学生信息

查找学生信息需要通过名字来进行查找。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def Seek_student(Name):
if Student_Dict:
is_seek = False
ids = 0
for ID in Student_Dict:
if Name == Student_Dict[ID]['姓名']:
ids += 1
is_seek = True
Sex = Student_Dict[ID]['性别']
Age = Student_Dict[ID]['年龄']
print(f'\n寻找到的学生{ids}\n学号:{ID}\n' +
f'姓名:{Name}\n性别:{Sex}\n年龄:{Age}\n')
if is_seek == False:
print('\n没有找到学生信息\n')
else:
print('\n学生列表不存在或为空\n')
2.3、删除学生信息

删除学生信息需要通过学号来进行删除,这样才具有唯一性

1
2
3
4
5
6
7
8
9
10
11
12
def del_stedent(ID):
if ID <= 0:
print('\n学号ID格式错误,学号必须为正整数\n即将回到选项页面\n')
return 0
if Student_Dict:
pop_student = Student_Dict.pop(ID, '\n没有该学生的信息\n')
if pop_student != '没有该学生的信息':
print('删除成功\n')
else:
print(pop_student)
else:
print('\n学生列表不存在或为空\n')
2.4、主函数

最后需要增加一个主函数,主函数的作用是把各个函数互相调用起来。

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
def main():
print("*"*30)
print("欢迎登陆学生信息录入系统".center(20))
try:
while True:
print("选择要进行的操作\n1、增加学生\n2、查找学生\n3、删除学生\n4、退出系统")
options = input("输入操作的选项:")
if options == '1':
print('\n学生信息新增页面')
try:
ID = int(input("学生学号:"))
Name = input("学生姓名:")
Sex = input("学生性别(男/女):")
Age = int(input("学生年龄:"))
except:
print('\n输入的信息格式错误,即将回到选项页面\n')
time.sleep(0.5)
continue

add_return = Add_students(ID, Name, Sex, Age)
if Student_Dict.get(ID, 0) != 0 and add_return != 0:
print('新增成功\n')
elif Student_Dict.get(ID, 0) == 0 and add_return != 0:
print('新增失败\n')
time.sleep(0.5)
continue
elif options == '2':
print('\n学生信息寻找页面')
Name = input("学生姓名:")
Seek_student(Name)
time.sleep(0.5)
continue
elif options == '3':
print('\n学生信息删除页面')
try:
ID = int(input("学生学号:"))
except:
print('\n输入的信息格式错误,即将回到选项页面\n')
time.sleep(0.5)
continue
del_stedent(ID)
time.sleep(0.5)
continue
elif options == '4':
print('\n正在退出系统')
time.sleep(0.5)
break
else:
print('\n请输入正确的选项,即将回到选项页面\n')
time.sleep(0.5)
continue
except KeyboardInterrupt: #捕捉因Ctrl+c退出程序导致的异常
print('\n正在退出系统')
time.sleep(0.5)

if __name__ == '__main__':
Student_Dict = {}
main()
3、总结

上面的练习实际上是一个很简单的python应用,更多的python脚本python程序都比上面的复杂的多得多,但是不管是什么程序,程序逻辑都是最重要的,我们应该多练习练习,掌握这些基础内容。