【问题标题】:Trying to make a list stop and display a message after a certain amount of entries, but the loop keeps going?尝试在一定数量的条目后停止列表并显示消息,但循环继续?
【发布时间】:2021-10-25 23:11:37
【问题描述】:

我正在完成一项作业,我们必须列出你打算在 Python 中学习的课程。您可以在列表中拥有的最大课程数量为 5。当输入第六个课程时,它应该要求您将另一个课程放入列表中以添加下一个条目。到目前为止,我的代码如下。当它运行时,它是一个无限循环,而不是在到达 6 时停止并显示消息。我该如何解决这个问题?

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? "))
    courseList.append(courses)
    course = course + 1
    if (courses == "Exit"):
        course = course - 1
#input to drop course
while (course >= 6):
    print(courseList)
    x = int(input("What course # will you drop? "))
    if(1<= x <=6):
        courseList.pop(x-1)
        course = course -1
        print(courseList)
    #error message
    else:
        print("Please select a # between 1-6. ")

【问题讨论】:

  • 如果某事物是可数的,使用“数字”。否则,使用“金额”。

标签: python list loops


【解决方案1】:

我已将两个 while 循环合并在一起,并添加了一些 if else
试试这个:

CourseList = []

while True:
    # Input to enter course name.
    course = input("What is the name of the course?\n")
    # Check if user wants to exit.
    if course == "Exit":
        break
    # Check the length of the list. If greater than 5, the user selects soemthing to drop.
    elif len(CourseList) >= 5:
        CourseList.append(course)
        # Show user the courses in the list
        print(CourseList)
        x = input("What course # will you drop?\n")
        # Check if x is a number or in range, if not, let the user input again.
        while x.isdigit() == False or x < '1' or x > '6':
            print("Please choose a number between 1 and 6")
            x = input("What course # will you drop?\n")
        x = int(x)
        CourseList.pop(x - 1)
        print(CourseList)
    # If none of above, append the course
    else:
        CourseList.append(course)

【讨论】:

    【解决方案2】:

    即使添加超过 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
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      • 2011-10-16
      • 1970-01-01
      • 2012-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多