如果你想在变量foo!= 5时做某事,初始值为5(例如)。
有谁知道更清洁的方式吗?一种方法是:
def try1():
foo = 5
aux = False
while (foo != 5) or (aux == False):
aux = True
foo = (random.randint(1,100) // (foo +1)) +1
print(foo)
如果你正在寻找一个repeat-until结构,那么Python中没有一个。但是,您可以通过创建迭代器来获得类似的东西。然后,您可以在for _ in ...
语句中使用该迭代器来获取所需的行为。
def repeatUntil(condition):
yield
while not condition(): yield
foo = 5
for _ in repeatUntil(lambda:foo==5):
foo = (random.randint(1,100) // (foo +1)) +1
print(foo)
或者repeatWhile()如果要表达延续条件而不是停止条件。 (在这两种情况下,条件将在循环结束时进行测试)
def repeatWhile(condition):
yield
while condition(): yield
foo = 5
for _ in repeatWhile(lambda:foo!=5):
foo = (random.randint(1,100) // (foo +1)) +1
print(foo)
请注意,这种方法将提供continue
的正确处理,因为while True: ... if foo==5: break
需要额外的代码(并且要格外小心)。
例如:
foo = 5
while True:
foo = (random.randint(1,100) // (foo +1)) +1
if someCondition == True: continue # loop will not stop even if foo == 5
print(foo)
if foo == 5: break
[更新]如果您更喜欢使用while语句并且不希望使用lambda:
,则可以创建一个loopUntilTrue()
函数来管理强制第一个传递:
def loopUntilTrue(): # used in while not loop(...):
firstTime = [True]
def loop(condition):
return (not firstTime or firstTime.clear()) and condition
return loop
foo = 5
reached = loopUntilTrue()
while not reached(foo==5):
foo = (random.randint(1,100) // (foo +1)) +1
print(foo)
请注意,您需要为每个while语句初始化loopUntilTrue()
的新实例。这也意味着你必须在使用这种方法的嵌套while循环中使用不同的变量名(对于reached
)
您可以使用退出条件执行相同的操作:
def loopUntilFalse(): # used in while loop(...):
firstTime = [True]
def loop(condition):
return (firstTime and not firstTime.clear()) or condition
return loop
foo = 5
outcome = loopUntilFalse()
while outcome(foo!=5):
foo = (random.randint(1,100) // (foo +1)) +1
print(foo)
如果条件在主体末尾为真,则使用显式中断的无限循环。
def try1():
foo = 5
while True:
foo = (random.randint(1,100) // (foo +1)) +1
print(foo)
if foo == 5:
break
另一种干净的方法是在循环之前评估一次语句。
def try1():
foo = 5
foo = (random.randint(1,100) // (foo +1)) +1
print(foo)
while foo != 5:
foo = (random.randint(1,100) // (foo +1)) +1
print(foo)
这样,foo生成一次,然后进入循环。