我正在尝试编写此代码,并且当我第一次运行该代码时,该函数有效,并且我能够将所有变量更新为列表并将该列表附加到course_catalogue。虽然,当我第二次运行函数时,出现了一个错误消息
UnboundLocalError:分配前已引用本地变量“可用性”。
有人知道为什么会这样吗?我该如何解决?
我程序的这个特定模块旨在向课程目录中添加一个包含所有信息(courseID,教师姓名等)的新课程,最终看起来像一个列表列表,每个特定课程都是一个列表在课程目录的更大列表中。
course_catalogue = []
def newcourse():
course_code = input('What is the course code? ')
department = input('Which department is this course in? ')
instructor = input("What is the instructor's name? " )
max_enrollment = input('What is the maximum enrollment for this course? ')
current_enrollment = input('How many students are currently enrolled in this course? ')
if max_enrollment > current_enrollment:
availability = 'Available'
if max_enrollment == current_enrollment:
availability = 'Full'
course_ID = [course_code, department, instructor, max_enrollment, current_enrollment, availability]
course_catalogue.append(course_ID)
答案 0 :(得分:2)
如果max_enrollment < current_enrollment
,您没有任何条件的限制,因此在这种情况下,可用性将不存在。
另一个问题是max_enrollment
和current_enrollment
都是字符串,而不是整数。
max_enrollment = int(input('What is the maximum enrollment for this course? '))
current_enrollment = int(input('How many students are currently enrolled in this course? '))
if max_enrollment > current_enrollment:
availability = 'Available'
elif max_enrollment == current_enrollment:
availability = 'Full'
elif max_enrollment < current_enrollment:
availability = 'Overfilled' # you can use whatever term you want here, or just swap the '==' for '<=' in the previous statement
答案 1 :(得分:1)
之所以发生这种情况,是因为您的if条件并不详尽。在您的代码中:
if max_enrollment > current_enrollment:
availability = 'Available'
if max_enrollment == current_enrollment:
availability = 'Full'
但是如果max_enrollment < current_enrollment
我建议将零件更改为:
if max_enrollment > current_enrollment:
availability = 'Available'
elif max_enrollment == current_enrollment:
availability = 'Full'
else:
availability = 'Something else'
答案 2 :(得分:0)
发生错误的原因是,如果条件为availability
,则变量if max_enrollment < current_enrollment:
将不存在
更改条件:
if max_enrollment > current_enrollment:
availability = 'Available'
if max_enrollment == current_enrollment:
availability = 'Full'
为
if max_enrollment > current_enrollment:
availability = 'Available'
else:
availability = 'Full'