声明statement:定义(创建)与赋值。
python主要由这两种语句组成。
表达式,对创建和赋值的对象进行一种使用,是一种计算,可以类比为定义或者执行一种函数。两者不同。
eval() 和exec()都接受字符串作为参数,exec执行的是声明语句,识别字符串为声明语句并执行,eval执行的是表达式而已。
exec也可以执行表达式的,,,总之感觉比eval好用。
>>> source_code= #定义了一个字符串,这个字符串是一个源代码。
'''
base_string='julyedu.com'
def test1(a,b):
return a+b
def test2(c):
x=7
print(c**2+x)
'''
>>> source_code
"
base_string='julyedu.com'
def test1(a,b):
return a+b
def test2(c):
x=7
print(c**2+x)
"
>>> eval(source_code) #由于source_code是一个全都是声明的字符串,所以只能用exec而不是eval,里面没有表达式。
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
eval(source_code)
File "<string>", line 2
base_string='julyedu.com'
^
SyntaxError: invalid syntax
>>> exec(source_code)
>>> test1(1,2) #显然已经执行了source_code。
3
>>> eval('a=0')
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
eval('a=0')
File "<string>", line 1
a=0
^
SyntaxError: invalid syntax
>>>