2 回答
TA贡献2080条经验 获得超4个赞
我能想到的最简单的方法如下。我修改了你的 2 个函数,并将“类”设为全局。
classes = {}
def checkOption(option):
global classes
if option == 1:
courseCount = courseCounter()
classes = addClasses(courseCount)
elif option == 2:
removeClasses()
elif option == 3:
viewCourseDetails()
elif option == 4:
viewSchedule()
def removeClasses():
courseName = input('Enter the class you would like to remove: ')
if courseName in classes:
del classes[courseName]
print(classes)
我希望这可以帮助你。
TA贡献1799条经验 获得超8个赞
通过 globals() 变量,以便您可以跨函数传递它:
def prompt():
print('MENU')
print('1 --> Add classes.')
print('2 --> Remove classes.')
print('3 --> View course details.')
print('4 --> View schedule.')
print('5 --> Quit.')
option = int(input('What would you like to choose? '))
while option < 1 or option > 5:
option = int(input('Please enter a valid numerical option: '))
return option
def checkOption(option):
if option == 1:
courseCount = 0
courseCount = courseCounter()
classes = addClasses(courseCount)
elif option == 2 :
if 'classes' in globals() :
removeClasses(globals()['classes'])
else :
print("Insert a class before!")
checkOption(1)
elif option == 3:
viewCourseDetails()
elif option == 4:
viewSchedule()
def courseCounter():
courseCount = input('Enter a numerical value of courses only (up to 4): ')
while courseCount.isnumeric() == False:
courseCount = input('Enter a NUMERICAL value of courses only (up to 4): ')
return int(courseCount)
def addClasses(courseCount):
classes = {}
i = 1
while i <= courseCount:
courseName = input('Enter a course name: ')
classes[courseName] = {}
classes[courseName]['Room Number'] = input('Enter a room number: ')
classes[courseName]['Instructor'] = input('Enter a instructor: ')
classes[courseName]['Meeting time'] = input('Enter a meeting time: ')
i = i + 1
globals()[ 'classes' ] = classes
return classes
def removeClasses(classes):
courseName = input('Enter the class you would like to remove: ')
if courseName in classes:
del classes[courseName]
print(classes)
def main():
option = prompt()
checkOption(option)
while option > 1 or option < 5:
if option == 5:
break
option = prompt()
checkOption(option)
main()
这适用于我的机器。这也检查类的存在或重定向用户来定义类。
注意 globals() 的行为(例如,为什么全局变量是邪恶的?)。否则,您可以定义一个对象(一个空字典)并通过函数传递它,填充它或检查它是否为空,这可能更安全。
添加回答
举报