2014-05-02 30 views
0

我想我遇到了編碼問題。當我更改爲utf-16時,錯誤更改爲第一行「導入溫度」簡單整數賦值語法錯誤無效

我安裝了Python 3.x,認爲它可能是版本問題,但是症狀相同。

我一直在運行的其他練習腳本工作正常。有任何想法嗎?

的Python表示在 「溫度= 0」

發生語法錯誤##### modules.py文件
def ftoc(temp): 
    return (5.0/9.0) * (temp - 32.0) 

def ctof(temp): 
    return (9.0/5.0) * temp + 32.0 
結果校正後
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文件內容 來自原始帖子的代碼。
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$ 
+1

你錯過了上一行一個右括號。 – roippi

回答

1

確實,這似乎是編碼問題。 \xFE是用於UTF-16編碼的BOM(\xFE \xFF)的一部分。

使用UTF-16作爲Python源代碼不是一個好主意。您無法使用編碼標記爲Python解析器提供源文件的源代碼編碼提示。如

# encoding: utf-8 

的詳細說明,請參見PEP-0263,以下是重要的信息的一部分:

Any encoding which allows processing the first two lines in the way indicated above is allowed as source code encoding, this includes ASCII compatible encodings as well as certain multi-byte encodings such as Shift_JIS. It does not include encodings which use two or more bytes for all characters like e.g. UTF-16. The reason for this is to keep the encoding detection algorithm in the tokenizer simple.

0
from temperature import ftoc 
from temperature import ctof 

這是多餘的,因爲你所有的進口溫度的功能與

import temperature 

你有語法錯誤,你的打印語句的結束失蹤括號。

您還有str(temperature)當你想要str(convTemp)。修復這些事情,我認爲它會正常工作。

+0

那真是令人尷尬。抱歉。漫長的一天。這是編碼錯誤似乎更加明顯的地方。 – user3594743

+0

「code'hostname $蟒蛇modules.py 回溯(最近通話最後一個): 文件 「modules.py」,1號線,在 進口溫度 文件「/用戶/ [名爲myUsername]/Dropbox的/蟒蛇/溫度.py「,第1行 SyntaxError:第1行文件/Users/[myusername]/Dropbox/python/temperature.py中的非ASCII字符'\ xfe',但未聲明編碼;詳情請參閱http://www.python.org/peps/pep-0263.html 主機名$ – user3594743

+0

修改過的程序對我來說只是將你的問題複製粘貼並編輯你在文本編輯器中的內容 - 我沒有得到編碼錯誤。 –