[英]How do I add multiple numbers from input in python, using the while statement. (or any other statement)
[英]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.