2015-02-10 118 views
2

在python中是否有until語句或循環?這是行不通的:直到語句/循環python?

x = 10 
list = [] 
until x = 0: 
    list.append(raw_input('Enter a word: ')) 
    x-=1 
+0

另請參見:[在Python中是否存在「do ... until」?](http://stackoverflow.com/questions/1662161/is-there-a-do-until-in-python)和[ Repeat-Until在python或等效循環](http://stackoverflow.com/questions/16758807/repeat-until-loop-in-python-or-equivalent) – John1024 2015-02-10 04:03:19

+0

Docs總是一個好地方 - [第一步朝着編程(https://docs.python.org/2.7/tutorial/introduction.html#first-steps-towards-programming) – wwii 2015-02-10 04:07:42

回答

1

相當於是一個while x1 != x2循環。

因此,你的代碼就變成了:

x = 10 
lst = [] #Note: do not use list as a variable name, it shadows the built-in 
while x != 0: 
    lst.append(raw_input('Enter a word: ')) 
    x-=1 
1
while x != 0: 
    #do stuff 

這將運行,直到找到x == 0

1

你並不真的需要算你有多少次的循環,除非你」重新做這個變量。相反,你可以使用一個for循環,會引發多達10次,而不是:

li = [] 
for x in range(10): 
    li.append(raw_input('Enter a word: ')) 

順便說一句,不要使用list作爲變量名,因爲這掩蓋了實際list方法。

0

Python的模擬直到環路與iter(iterable, sentinel)成語:

x = 10 
list = [] 
for x in iter(lambda: x-1, 0): 
    list.append(raw_input('Enter a word: ')) 
  • 我不得不構建一個簡單的拉姆達用於演示目的;這裏簡單的range()就足夠了,就像@Makoto建議的那樣。