Domanda

I think I'm running into encoding issues. When I change to utf-16 the error changes to the first line "import temperature"

I installed Python 3.x thinking maybe it was a version issue but same symptoms.

Other exercise scripts I've been running have worked fine. Any ideas?

Python indicates the syntax error occurs at "temp = 0"

##### modules.py file
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 file contents
def ftoc(temp):
    return (5.0/9.0) * (temp - 32.0)

def ctof(temp):
    return (9.0/5.0) * temp + 32.0
Results after correcting code from original post.
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$
È stato utile?

Soluzione

This seems to be encoding problem, indeed. The \xFE is part of BOM(\xFE \xFF) for UTF-16 encodings.

Using UTF-16 as Python source code is not a good idea. You're not able to give Python parser a hint of the source code encoding of the source file using the encoding mark. Such as

# encoding: utf-8

See PEP-0263 for detailed explanation, and below is part of important information:

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.

Altri suggerimenti

from temperature import ftoc
from temperature import ctof

This is redundant because you imported all the temperature functions with

import temperature

You have syntax errors, missing parens at the end of your print statements.

Also you have str(temperature) when you want str(convTemp). Fix these things and I think it will work fine.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top