Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
启动Python';而';在定义条件之前循环_Python - Fatal编程技术网

启动Python';而';在定义条件之前循环

启动Python';而';在定义条件之前循环,python,Python,我有一段执行函数的代码,然后根据该输出决定是否应该重复: while (function_output) > tolerance: function_output = function(x) 问题是while循环在定义“function_output”之前不会启动,但它是在循环中定义的。目前我有: function_output = function(x) while (function_output) > tolerance: function_output =

我有一段执行函数的代码,然后根据该输出决定是否应该重复:

while (function_output) > tolerance:
    function_output = function(x)
问题是while循环在定义“function_output”之前不会启动,但它是在循环中定义的。目前我有:

function_output = function(x)
while (function_output) > tolerance:
    function_output = function(x)

但是有没有一种方法可以让这个循环开始,而不必重复函数一次呢?

使用
break
语句从循环中退出

while True:
    if function_output(x) > tolerance:
        break

使用
break
语句退出循环

while True:
    if function_output(x) > tolerance:
        break

这个式样怎么样。您可能需要选择一个更好的变量名

should_continue = True
while should_continue:
    should_continue = ( function(x) > tolerance )

这个式样怎么样。您可能需要选择一个更好的变量名

should_continue = True
while should_continue:
    should_continue = ( function(x) > tolerance )

python中没有这样的东西。既不是
执行while
,也不是

while (x = f() > 5):
  dostuff
类似于
C
和类似的语言

类似的构造。你已经在做的是最好的方法

另一方面,如果您想以
do-while
的方式进行,建议的方法是

while True:
    if f() > tolerance:
       break

python中没有这样的东西。既不是
执行while
,也不是

while (x = f() > 5):
  dostuff
类似于
C
和类似的语言

类似的构造。你已经在做的是最好的方法

另一方面,如果您想以
do-while
的方式进行,建议的方法是

while True:
    if f() > tolerance:
       break


在时模拟一个
操作
while True:stuff()if fail\u condition:break
No,python在循环之前没有“do”——“而”loopfunction\u output=tolerance+1?@TIF:值得一提的是,您的第二块代码是执行此操作的标准方法。OP是正确的,因为它认为第二种方法不好:它有重复的代码。模拟一个
do while
while True:stuff()如果fail\u条件:break
No,python在循环之前没有“do”-“而”loopfunction\u output=tolerance+1?@TIF:无论如何,你的第二块代码是实现这一点的标准方法。OP是正确的,如果认为第二种方法不好:它有重复的代码。我认为你的条件是颠倒的-那是在OPs代码中继续循环的条件我认为你的条件是颠倒的-那是在OPs代码中继续循环的条件,而这当然是一种选择,IDLEHAND的代码重复性更少。@ctrl alt delor,重复了什么,函数调用?如果我必须权衡一个重复的函数调用和创建一个新变量,我知道我更喜欢哪一个。@Jpp我同意如果只是一个函数调用,但是如果有很多或参数,我会这样做。或者封装。虽然这当然是一种替代方法,但它并不比OP的实现好多少。@Idlehands is的代码重复次数较少。@ctrl-alt-delor,什么是重复的,函数调用?如果我必须权衡一个重复的函数调用和创建一个新变量,我知道我更喜欢哪一个。@Jpp我同意如果只是一个函数调用,但是如果有很多或参数,我会这样做。或者封装。@timgeb:有用(虽然看起来有点难看)。让我们期待一个
do while
也…@timgeb:有用(虽然看起来有点难看)。让我们期待一个
同时也做
。。。