在 Python 中执行一串代码

pythonserver side programmingprogramming更新于 2025/10/19 5:32:17

有时您需要将整个代码块作为字符串,并希望此代码作为更大的 Python 程序的一部分执行。在本文中,我们将了解如何将代码作为字符串传递给变量,然后在包装程序中使用该变量,然后包装程序将该程序作为 Python 代码执行。

exec() 函数用于执行代码。代码必须嵌入在三个“内。

示例

code = """
numbers = [11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
   if num%2 == 0:
      print ('the list contains an even number')
      break
else:
   print ('the list doesnot contain even number')
"""
exec(code)

输出

运行上述代码得到以下结果 −

the list does not contain even number.

相关文章


有用资源