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

如何让python中的循环返回到原始while语句。,python,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

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

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'

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

一旦选择,该选项将永远保留,因为
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

有效地…
注册
作为一个变量在第一个输入语句之后不会发生变化。这意味着,当您开始运行此代码时,您将被赋予的任何值所困扰

因为您似乎想要类似菜单的功能,所以实现这一点的一个更简单的方法是将所有内容拆分为方法

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

注册在while循环中不会更改。只需通过
if
更改
while
,并在条件相同时进行全局循环使用
elif
exclusive@Barmar:但是这些条件已经相互排斥,因此进一步隔离它们似乎没有必要。不过,我把这留给读者作为一个练习。重点是告诉Python它们是独占的,这样在它已经匹配了
a
之后就不用麻烦检查
e
d
。这也让代码的读者更清楚地知道这些是独占的情况。@Barmar:再次……这真的取决于读者。我上面的代码更多的是示例和说明。