码迷,mamicode.com
首页 > 其他好文 > 详细

表达式与声明的区别。

时间:2020-06-13 23:22:30      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:str   字符串   pre   没有   参数   module   的区别   exec   syn   

声明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
"\nbase_string=‘julyedu.com‘\n\ndef test1(a,b):\n return a+b\n\ndef test2(c):\n x=7\n print(c**2+x)\n"
>>> 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
>>> 

  

表达式与声明的区别。

标签:str   字符串   pre   没有   参数   module   的区别   exec   syn   

原文地址:https://www.cnblogs.com/zy1120192493/p/13122047.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!