如何让python中的循环返回到原始while语句。

2024-06-28 10:50:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建的循环在询问要添加哪个类以及何时删除一个类时运行平稳。但是,每当我在删除一个类之后尝试添加一个类时,程序就结束了,而不是返回到循环中添加一个类。我在程序中哪里出错了。下面是代码

RegisteredCourses=[]
Registration=raw_input('Enter A to add a course, D to drop a course and E to exit.')
while Registration=='a':
    Course=raw_input('What course do you want to add?')
    RegisteredCourses.append(Course)
    print RegisteredCourses
    Registration=raw_input('Enter A to add a course, D to drop a course and E to exit.')
while Registration=='d':
    DropCourse=raw_input('What course do you want to drop?')
    RegisteredCourses.remove(DropCourse)
    print RegisteredCourses
    Registration=raw_input('Enter A to add a course, D to drop a course and E to exit.')
while Registration=='e':
    print 'bye'

Tags: andto程序addinputrawexitregistration
2条回答

实际上…Registration作为一个变量,在它的第一个输入语句之后不会改变。这意味着当你开始运行这段代码的时候,你会被你赋予它的任何价值所束缚

既然您似乎想要类似于菜单的功能,那么实现这一点的一个更简单的方法就是将所有内容拆分为方法

def add_course():
    Course=raw_input('What course do you want to add?')
    RegisteredCourses.append(Course)
    print RegisteredCourses

# Other methods for other functions

在应用程序的主要关键部分中,有一个简单的while True循环

while True:
    registration = raw_input('Enter A to add a course, D to drop a course and E to exit.')
    if registration == 'a':
        add_course()
    # Other methods
    if registration == 'e':
        print 'bye'
        break

没有1个外部循环请求用户输入,有3个内部循环。这是错误的

一旦选中,选项将永远保留,因为while循环一旦进入,将永远循环(条件的值在循环中不会改变)

相反,做一个无限循环,把你的while改成if/elif,并且只问这个问题一次:

RegisteredCourses=[]
while True:
    Registration=raw_input('Enter A to add a course, D to drop a course and E to exit.')
    if Registration=='a':
        Course=raw_input('What course do you want to add?')
        RegisteredCourses.append(Course)
        print RegisteredCourses
    elif Registration=='d':
        DropCourse=raw_input('What course do you want to drop?')
        RegisteredCourses.remove(DropCourse)
        print RegisteredCourses
    elif Registration=='e':
        print 'bye'
        break  # exit the loop

相关问题 更多 >