简单整数赋值时的无效语法错误
我觉得我遇到了编码问题。当我把编码改成utf-16时,错误信息变成了第一行“import temperature”。
我安装了Python 3.x,以为可能是版本的问题,但结果还是一样。
我之前运行的其他练习脚本都没问题。有没有什么建议?
Python提示语法错误出现在“temp = 0”这一行。
##### modules.py 文件import temperature
temp = 212
convTemp = temperature.ftoc(temp)
print("The converted temp is " + str(convTemp))
temp = 0
convTemp = temperature.ctof(temp)
print("The converted temp is " + str(convTemp))
#### temperature.py 文件内容
def ftoc(temp):
return (5.0/9.0) * (temp - 32.0)
def ctof(temp):
return (9.0/5.0) * temp + 32.0
修正代码后的结果。
hostname$ python modules.py
Traceback (most recent call last):
File "modules.py", line 1, in <module>
import temperature
File "/Users/[myusername]/Dropbox/python/temperature.py", line 1
SyntaxError: Non-ASCII character '\xfe' in file /Users/[myusername]/Dropbox/python/temperature.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
hostname$
2 个回答
0
from temperature import ftoc
from temperature import ctof
这段代码有点多余,因为你已经通过
import temperature
导入了所有的温度函数。
你这里有语法错误,打印语句的末尾缺少括号。
另外,你用的是 str(temperature)
,其实应该用 str(convTemp)
。把这些问题修正一下,我觉得代码就能正常运行了。
1
这看起来确实是个编码问题。\xFE
是 UTF-16 编码中一个叫做 BOM(\xFE \xFF
) 的部分。
在 Python 源代码中使用 UTF-16 并不是个好主意。因为你不能通过编码标记来告诉 Python 解析器源文件的编码方式。比如说:
# encoding: utf-8
想要了解更多,可以查看 PEP-0263
的详细解释,下面是一些重要信息:
任何能够处理前两行的编码都可以作为源代码编码,这包括与 ASCII 兼容的编码,以及某些多字节编码,比如 Shift_JIS。但不包括那些所有字符都使用两个或更多字节的编码,比如 UTF-16。这样做的原因是为了让编码检测算法在分词器中保持简单。