让用户输入周一到周五的课程名称,每天的课程依次输入,逗号隔开
程序输出课程表表格如下:
---------------------------------
周一 周二 周三 周四 周五
语文 数学 体育 英语 道德
数学 数学 语文 英语 体育
数学 数学 语文 英语 体育
语文 数学 体育 英语 道德
---------------------------------
用户可以查询某一天的第几节课。
实现
题目要求已实现,并且使用转为json格式存入本目录.cs
文件。
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
import json
from functools import reduce
#Class name data file's location and name
CS_FILE="./.cs"
#I know that using two-dimension is better than this way,but I just want to practice the function of 'zip'.
CLASS_SCHEDULE={}
CLASS_NAME=[[],[],[],[],[]]
WEEK_NAME=['Monday','Tuesday','Wednesday','Thursday','Friday']
#Integrate date
def init():
global CLASS_SCHEDULE
#'zip' function will match location of each elements of list to integrate a object whose type is dict.
CLASS_SCHEDULE=dict(zip(WEEK_NAME,CLASS_NAME))
def mainView():
print(f"{'CLASS SCHEDULE BY JASON':#^50s}")
print(f"{'':#^50s}")
print(f"{'1.PREVIEW 2.INPUT 3.MODIFY 4.QUERY 5.SAVE 6.EXIT':#^50s}")
print(f"{'':#^50s}")
print(f"{'':#^50s}")
#Fill space
#return row count.
def addSpace(className):
maxRow=len(max(*className,key=len))
for x in className:
while len(x)<maxRow:
x.append(f"{'':^10s}")
return maxRow
def preview():
i=0
row=addSpace(CLASS_NAME)
print(f"{'':-^50}")
#Day Title
print(reduce(lambda x,y:f"{x:^10s}"+f"{y:^10s}",WEEK_NAME))
#Using two-dimension will be better than this way.
while i<row:
for k,v in CLASS_SCHEDULE.items():
print(f"{v[i]:^10s}",end='')
print()
i+=1
print(f"{'':-^50}")
def inputClass():
while True:
#Actully,using 'if else' is better than this way,because the dict's 'get' function or 'in' keyword isn't to raise exception in default way.
try:
i=1
tempClassLS=[]
dayName=input(f"[ROOT/INPUT]{'>':#>2s}Please input the day name of that you want to add class:")
if dayName not in CLASS_SCHEDULE:
raise Exception('error by Jason.')
while True:
tempClassName=input(f"[ROOT/INPUT]{'>':#>2s}Please input the lesson-{i}'s name :")
tempClassLS.append(tempClassName)
userIntention=input(f"[ROOT/INPUT]{'>':#>2s}Continue to add on {dayName}?[y/n|yes/no]:")
#Up to now,I haven't found the 'equal' function as Java in python environment.
if userIntention=="yes" or userIntention=="y":
i+=1
continue
else:
break
#Don't assign value to this element directly,because it will cause address different between 'CLASS_SCHEDULE' and 'CLASS_NAME'
CLASS_SCHEDULE[dayName].clear()
CLASS_SCHEDULE[dayName].extend(tempClassLS)
userIntention=input(f"[ROOT/INPUT]{'>':#>2s}Continue to add in other days?[y/n|yes/no]:") #Up to now,I haven't found the 'equal' function as Java in python environment.
if userIntention=="yes" or userIntention=="y":
continue
else:
break
except:
print("Please input again!Such as 'Monday,Tuesday...'")
continue
finally:
pass
#To return a object address for modify function will be better than this way which only used by one operation,but...I don't want to restructure it. I am a lazy boy,emm...
def query():
params=input(f"[ROOT/QUERY]{'>':#>2s}Please input the specific date[DayName,LessonNumber]:").split(',')
if params[0] in CLASS_SCHEDULE:
if int(params[1]) <= len(CLASS_SCHEDULE[params[0]]):
print(f"Class Name:{CLASS_SCHEDULE[params[0]][int(params[1])-1]}" if not CLASS_SCHEDULE[params[0]][int(params[1])-1].strip()=='' else "You don't have classes at this point-in-time.")
else:
print("You don't have classes at this point-in-time.")
else:
print("Please input again!Such as 'Monday,Tuesday...'")
def modify():
params=input(f"[ROOT/MODIFY]{'>':#>2s}Please input the specific date[DayName,LessonNumber]:").split(',')
CLASS_SCHEDULE[params[0]][int(params[1])-1]=input(f"[ROOT/MODIFY]{'>':#>2s}Please input class name:")
def main():
mainView()
readCS()
init()
while True:
try:
#'match' is new keyword in the environment of Python 3.10,if raise error,please upgrade your python environment or modify the syntax by yourself.
match input(f"[ROOT]{'>':#>2s}Please input instruction:"):
case '1':
preview()
case '2':
inputClass()
case '3':
modify()
case '4':
query()
case '5':
saveCS()
case '6':
print("Good Bye!")
quit()
case _:
print("Please input again!")
except Exception as e:
print("Input error! Please input it again.")
#print("Error:",e)
continue
finally:
pass
#--FILE OPERATION---
def saveCS():
#The keyword 'with' is similar to Csharp's keyword 'using' which will always close IO streem automatically.
with open(CS_FILE,"w",encoding="utf-8") as f:
#Serilization:Transform python object to json's format string directly,and write to file subsequently.
json.dump(CLASS_NAME,f)
print("Already saved!")
def readCS():
#bind variable scope
global CLASS_NAME
try:
with open(CS_FILE,'r',encoding="utf-8") as f:
#Return python object directly.
CLASS_NAME=json.load(f)
except:
pass
finally:
pass
#--------
#init()
#addSpace(CLASS_NAME)
#print(CLASS_NAME)
#preview()
#CLASS_NAME[0].append('hhhh')
#print(CLASS_SCHEDULE)
#saveCS()
main()
输出
#############CLASS SCHEDULE BY JASON##############
##################################################
#1.PREVIEW 2.INPUT 3.MODIFY 4.QUERY 5.SAVE 6.EXIT#
##################################################
##################################################
[ROOT]#>Please input instruction:2
[ROOT/INPUT]#>Please input the day name of that you want to add class:Monday
[ROOT/INPUT]#>Please input the lesson-1's name :Chinese
[ROOT/INPUT]#>Continue to add on Monday?[y/n|yes/no]:y
[ROOT/INPUT]#>Please input the lesson-2's name :Math
[ROOT/INPUT]#>Continue to add on Monday?[y/n|yes/no]:n
[ROOT/INPUT]#>Continue to add in other days?[y/n|yes/no]:y
[ROOT/INPUT]#>Please input the day name of that you want to add class:Friday
[ROOT/INPUT]#>Please input the lesson-1's name :Society
[ROOT/INPUT]#>Continue to add on Friday?[y/n|yes/no]:y
[ROOT/INPUT]#>Please input the lesson-2's name :English
[ROOT/INPUT]#>Continue to add on Friday?[y/n|yes/no]:y
[ROOT/INPUT]#>Please input the lesson-3's name :PPP
[ROOT/INPUT]#>Continue to add on Friday?[y/n|yes/no]:n
[ROOT/INPUT]#>Continue to add in other days?[y/n|yes/no]:n
[ROOT]#>Please input instruction:1
--------------------------------------------------
Monday Tuesday Wednesday Thursday Friday
Chinese Society
Math English
PPP
--------------------------------------------------
[ROOT]#>Please input instruction:4
[ROOT/QUERY]#>Please input the specific date[DayName,LessonNumber]:Friday,1
Class Name:Society
[ROOT]#>Please input instruction:A
Please input again!
[ROOT]#>Please input instruction:5
Already saved!
[ROOT]#>Please input instruction:6
Good Bye!
Q.E.D.