[每日一记] Python报错 综述
提纲
-- Syntax errors
-- Static semantic errors
-- Full semantic errors
--
使用一门语言,不论是自然语言还是编程语言,我们需要注意两个方面:Syntax(句法)和 Semantics(语义)。
一、
所谓Syntax(句法),就是一句话、或一个表达式的正确的语法结构。
例如,英语中“I eat meat.”是正确的句法,“I meat eat”就不是。
在Python中,以下几种情况都会归为「SyntaxError: invalid syntax」,因为这些错误都属于语法结构的错误:
1. 变量命名不合规范
>>> a = 1 >>> 1a = 1 File "<stdin>", line 1 1a = 1 ^ SyntaxError: invalid syntax
2. 标点的错误
>>> a = 1; >>> a = 1;; File "<stdin>", line 1 a = 1;; ^ SyntaxError: invalid syntax
3. 表达式语序错误
>>> print 1 1 >>> 1 print File "<stdin>", line 1 1 print ^ SyntaxError: invalid syntax
4. 无意义的表达
>>> printf 1 File "<stdin>", line 1 printf 1 ^ SyntaxError: invalid syntax >>> 1 2 3 File "<stdin>", line 1 1 2 3 ^ SyntaxError: invalid syntax >>> i eat meat File "<stdin>", line 1 i eat meat ^ SyntaxError: invalid syntax >>> Love trumps hate. File "<stdin>", line 1 Love trumps hate. ^ SyntaxError: invalid syntax
在Python中,还有一类错误,在广义上讲属于Syntax(句法)错误,即「IndentationError: unexpected indent」(缩进错误):
>>> a File "<stdin>", line 1 a ^ IndentationError: unexpected indent
(👆 从上面我们可以看到,在Python中不允许行首空一格再写表达式。)
二、
Semantics意为语义。
编程语言的语义可以分为 static semantics 和 full semantics。
Static semantics常被直译为“静态语义”,一个很不直观的翻译。其实,Static semantics关注一个个表达式是否有意义,不要被“静态”这个词弄晕了。(不过,习惯了这个词之后,你会理解“静态”的意义)
比如,NameError
>>> print a Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'a' is not defined
比如,TypeError
>>> 'a' + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects
我们在日常里遇到的大部分程序报错都是static semantic errors(静态语义错误)。因为我们很难犯Syntax错误这种低级错误,而机器不会帮我们检测full semantic error这种高级错误。
三、
Full semantics关注程序运行时会发生什么。
一个句法上正确、static语义上也有意义的程序,如果运行过程中形成了死循环,或者崩溃,或者在运行中出错但输出了一个看似正确的结果,便是在full semantics上出现了问题。
机器一般不会帮我们发现full semantic errors,所以我们需要自己想办法来避免犯这类编程错误。

浙公网安备 33010602011771号