即使添加超过 6 个值,循环也不会停止的原因是,第一个 'while' 循环的条件要求它只有在输入 "exit" 时才会停止。
这实际上意味着您不会因为任何其他原因而结束第一个 while 循环。
要解决这个问题,你应该考虑你想要做什么,我们最初的回复是"if the user tries to add more than 5 courses, he should be prompted to remove an existing course"。很明显,这里的 if 条件就足够了。
但后来我们意识到,如果用户试图删除不存在的课程(输入不在 1 和 6 之间)会怎样。那么我们认为"while the 6th course is being added, keep prompting for removing a course, until successfully removed"。 (这个问题可以用干净的方式处理,这样我们直观的第一反应就出现在代码中,Read until the end)
已阅读以上推理;
考虑以下几点:
courseList = []
#sets beginning of loop to 0
course = 0
courses = "none"
#input to enter course name
while (courses != "Exit"):
courses = str(input("What is the name of the course? "))
# Move this to the top, since if user is trying to exit the loop, nothing else needs to be done but that
if (courses == "Exit"):
break
### Add this ###
while course >= 5: # This is essentially also implying if course >= 5 if you think about it
print(courseList)
x = int(input("What course # will you drop? "))
if 1 <= x <= 5:
courseList.pop(x-1)
course = course - 1
else:
print("Please select a # between 1-5. ")
### END ###
courseList.append(courses)
course = course + 1
现在,我还想补充一点,第一个中的第二个 while 循环可能会因为不干净而脱落。因此,您可能希望将其移至函数中。
def removeCourse(lst, course):
while course >= 5:
print(courseList)
x = int(input("What course # will you drop? "))
if 1 <= x <= 5:
courseList.pop(x-1)
course = course - 1
else:
print("Please select a # between 1-5. ")
然后使代码变为:
while (courses != "Exit"):
courses = str(input("What is the name of the course? "))
if (courses == "Exit"):
break
if course >= 5: # Note how we change this to the if condition now, which was our initial response to the problem, because the function handles the case where the input is not valid
removeCourse(courseList, course)
courseList.append(courses)
course = course + 1