Python3 turns string into executable command
Execution of python string type code
eval()
Execute string type code. And return the final resultexec()
Execute string type codecompile()
Encode string type code. Code objects can beexec
executed oreval()
evaluated through statements
#输入:8+9
s1 = input("请输入a+b:")
# 17 可以动态的执行代码. 代码必须有返回值
print(eval(s1))
s2 = "for i in range(5): print(i)"
# exec 执行代码不返回任何内容
a = exec(s2)
# 0
# 1
# 2
# 3
# 4
print(a)
#None
eval() turns a string into an executable command
Reference: https://blog.csdn.net/weixin_34128237/article/details/91933587
Python3
Usage eval()
methods can be 字符串
turned into 系统执行的命令
. eval()
Functions can be used to run string expressions.
For example:
# eval将字符串作为代码执行
n = input('请输入一个1000--9999的整数')
s = eval(f'{
n[0]}+{
n[1]}+{
n[2]}+{
n[3]}')
print(f'{
n}每一位的数字之和为:{
s}')
exec() dynamically executes code
exec()
Functions can execute more complex string code.
Reference: https://www.runoob.com/python/python-func-exec.html
exec("""
def func():
print(" 我是周杰伦")
""")
# 打印结果:我是周杰伦
func()
compile() compiles a string into bytecode
https://www.runoob.com/python/python-func-compile.html
compile()
Function compiles a string into byte code.
code1 = "for i in range(3): print(i)"
# compile并不会执行你的代码.只是编译
com = compile(code1, "", mode="exec")
# 执行编译的结果
exec(com)
code2 = "5+6+7"
com2 = compile(code2, "", mode="eval")
print(eval(com2))
code3 = "name = input('请输入你的名字:')" # 输入:hello
com3 = compile(code3, "", mode="single")
exec(com3)
print(name)