1.定义一个类描述数字时钟
要求:给定一个时间,例如15:50:00,则最终的效果为,如图:
15:50:01
15:50:02
15:50:03
15:50:04
15:50:05
15:50:06
15:50:07
15:50:08
15:50:09
15:50:10
15:50:11
15:50:12
15:50:13
15:50:14
15:50:15
15:50:16
15:50:17
15:50:18
15:50:19
15:50:20
15:50:21
既然是做一个时钟,我们首先能想到是引入时间模块。
import time
class Clock(object):
def show_time(self):
count=0
while count<20:
t = time.strftime("%H:%M:%S", time.localtime())
print(t)
time.sleep(1)
count+=1
if __name__ =="__main__":
result=Clock()
result.show_time()
结果:
10:54:53
10:54:54
10:54:55
10:54:56
10:54:57
10:54:58
10:54:59
10:55:00
10:55:01
10:55:02
10:55:03
10:55:04
10:55:05
10:55:06
10:55:07
10:55:08
10:55:09
10:55:10
10:55:11
10:55:12
显然这样不太对,这段代码无法写入时间,从而让程序计算按照题意进行时间的计算。之后我考虑引入datetime模块,但是发现datetime模块必须带年,月,日。也不能使用。所以我考虑用input来实现时间的输入。
# 导入时间模块
import time
class Clock(object):
# 时间初始化
def __init__(self, h, m, s):
self.hour = h
self.minute = m
self.second = s
# 走字
def run(self):
# 秒+
self.second += 1
if self.second == 60:
self.second = 0
self.minute += 1
if self.minute == 60:
self.minute = 0
self.hour += 1
if self.hour == 24:
self.hour = 0
# 显示
def show(self):
# 不足两位的在数字前补0
print("%02d:%02d:%02d"%(self.hour,self.minute,self.second))
def clocktime():
h = int(input("请输入小时"))
m = int(input("请输入分钟"))
s = int(input("请输入秒钟"))
clock = Clock(h,m,s)
while True:
clock.show()
time.sleep(1)
clock.run()
print(clocktime())
结果:
15:50:00
15:50:01
15:50:02
15:50:03
15:50:04
15:50:05
15:50:06
15:50:07
15:50:08
15:50:09
15:50:10
15:50:11
15:50:12
15:50:13
15:50:14
15:50:15
15:50:16
15:50:17
15:50:18
15:50:19
15:50:20
15:50:21
2.定义管理员类:
管理员有属性(name,password),
可以创建学校、创建课程、创建老师
class School(object):
# 初始化
def __int__(self):
self.name = "admin"
self.pwd = 12345
# 管理学校
def createSchool(self,school):
self.school = school
# 管理老师
def createTeacher(self,teacher):
self.teacher = teacher
# 管理课程
def createCourse(self,course):
self.course = course
s = School()
while True:
# 设置选项
l=int(input("请选择您要进行的操作:\n1.选择学校\n2.选择课程\n3.选择老师\n4.退出\n"))
if l == 1:
s.createSchool(input("请输入要选择的学校:\n"))
print("您选择了"+s.school)
elif l == 2:
s.createCourse(input("请输入要选择的课程:\n"))
print("您选择了" +s.course)
elif l == 3:
s.createTeacher(input("请输入要选择的老师:\n"))
print("您选择了" +s.teacher)
else:
break
结果:
请选择您要进行的操作:
1.选择学校
2.选择课程
3.选择老师
4.退出
1
请输入要选择的学校:
扣丁学堂
您选择了扣丁学堂
请选择您要进行的操作:
1.选择学校
2.选择课程
3.选择老师
4.退出
2
请输入要选择的课程:
python
您选择了python
请选择您要进行的操作:
1.选择学校
2.选择课程
3.选择老师
4.退出
3
请输入要选择的老师:
摩登
您选择了摩登
请选择您要进行的操作:
1.选择学校
2.选择课程
3.选择老师
4.退出
4
Process finished with exit code 0