簡體   English   中英

如何在python中獲得循環以返回原始的while語句。

[英]How do I get a loop in python to return to the original while statement.

我創建的循環在詢問要添加哪個類和刪除類時平穩運行。 但是,每當我嘗試在刪除一個類之后添加一個類時,該程序便會結束,而不是回到循環中添加一個類。 我在程序中哪里出錯了。 下面是代碼。

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更改您的while ,並僅詢問一次問題:

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

有效地... 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM