Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.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 内联函数hack只使用内联if-else_Python_Python 3.x - Fatal编程技术网

Python 内联函数hack只使用内联if-else

Python 内联函数hack只使用内联if-else,python,python-3.x,Python,Python 3.x,最近的一个问题让我思考,是否有可能采取以下措施: def defA(flag) : return "value = 'yes'" if flag else "continue" flag = False #n can be a reasonable number like 100 for x in range(n): #some logic that may change the flag exec(defA(flag)) 在这里,如果标志为true,您将得到一个变

最近的一个问题让我思考,是否有可能采取以下措施:

def defA(flag) : 
    return "value = 'yes'" if flag else "continue"

flag = False
#n can be a reasonable number like 100
for x in range(n):
    #some logic that may change the flag
    exec(defA(flag))
在这里,如果标志为true,您将得到一个变量赋值,否则将继续for循环,但它会给我一个奇怪的错误:

SyntaxError: 'continue' not properly in loop

这是可能的还是我应该放弃它?

因为exec不会将上下文传递给正在执行的语句

pass可以在任何地方使用,因此上下文并不重要。continue只能在循环的上下文中使用,但该上下文对exec不可用

如果循环本身也是已执行代码的一部分,则只能在exec语句中使用continue:

f='对于范围(n)中的x:if(标志)continue'exec f


换句话说,您只能对完整语句使用exec,其中单个continue(或break)语句不完整。

请放手。。。请注意,
if-flag:value='yes'
应该只在一行上工作,但它仍然使控制流难以读取。@AndrasDeak我同意你的观点,重复的问题回答了我的问题,谢谢你的评论:)