直到语句/循环python?
问题描述:
在python中是否有until
语句或循环?这是行不通的:直到语句/循环python?
x = 10
list = []
until x = 0:
list.append(raw_input('Enter a word: '))
x-=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
答
while x != 0:
#do stuff
这将运行,直到找到x == 0
答
你并不真的需要算你有多少次的循环,除非你”重新做这个变量。相反,你可以使用一个for
循环,会引发多达10次,而不是:
li = []
for x in range(10):
li.append(raw_input('Enter a word: '))
顺便说一句,不要使用list
作为变量名,因为这掩盖了实际list
方法。
答
Python的模拟直到环路与iter(iterable, sentinel)
成语:
x = 10
list = []
for x in iter(lambda: x-1, 0):
list.append(raw_input('Enter a word: '))
- 我不得不构建一个简单的拉姆达用于演示目的;这里简单的
range()
就足够了,就像@Makoto建议的那样。
另请参见:[在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
Docs总是一个好地方 - [第一步朝着编程(https://docs.python.org/2.7/tutorial/introduction.html#first-steps-towards-programming) – wwii 2015-02-10 04:07:42