在Python中执行代码字符串
有时候,您需要将整个代码块作为字符串,并希望将此代码作为更大的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.
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短