Invalid Syntax Error On Simple Integer Assignment [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
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$

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.

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.

Related

Encoding issue during reading excel file in Python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I use read_excel from pandas library to read excel content and convert it to JSON. I am struggling with encoding issue. Non english characters are encoded like "u652f\u63f4\u8cc7\u8a0a".
How can I resolve this issue?
I tried
wb = xlrd.open_workbook(excel_filePath, encoding_override='ISO-8859-1')
new_data = pd.read_excel(wb)
Also
with open(excel_filePath, mode="r", encoding="utf-8") as file:
new_data = pd.read_excel(excel_filePath)
I tried this code with encodings like: utf-8, utf-16, utf-16, latin1...
From the docs of the json module:
The RFC requires that JSON be represented using either UTF-8, UTF-16, or UTF-32, with UTF-8 being the recommended default for maximum interoperability.
As permitted, though not required, by the RFC, this module’s serializer sets ensure_ascii=True by default, thus escaping the output so that the resulting strings only contain ASCII characters.
Maybe surprising that in this day-and-age the module defaults to escaping non-ASCII (probably for backwards compatibility), so just override that behavior with ensure_ascii=false:
with open(json_filePath, 'w') as f:
json.dump(new_json, f, ensure_ascii=False)

Python, unexpected EOF while parsing error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am a complete beginner in Python, having used R quite a lot before.
I am trying to write a multiline string which is very straightforward in R but I receive an error that stumps me, I have googled around everywhere but the suggested solutions have not worked.
When I try to use parentheses as I have seen suggested:
multiline = ("Hello,"
" my name is"
" James")
I receive:
multiline = ("Hello,"
File "<ipython-input-56-f67f7efad636>", line 1
multiline = ("Hello,"
^
SyntaxError: unexpected EOF while parsing
Similarly I tried triple quotes, also suggested:
multiline = """Hello,
my name is
James"""
I receive:
multiline = """Hello,
File "<ipython-input-58-0879a928a2ee>", line 1
multiline = """Hello,
^
SyntaxError: EOF while scanning triple-quoted string literal
I am sure I will be missing something blindingly obvious to more experienced Python users but any help would be greatly appreciated.
Thanks very much
Apparently, this is neither an issue with python, ipython or spyder. The mistake is using the incorrect command to run your code. You probably used Run Selection or Current Line, while the cursor was in the first line of the multiline strings. This command doesn't consider the context, so it essentially pastes the line into the interpreter and runs. Your first error was caused by python not finding the closing parentheses. Your second error is python not finding the closing triple quotes. In spyder, one typically makes code cells with #%% and runs them with CTRL+ENTER or SHIFT+ENTER. That should fix your problem.

How to remove nonprintable characters in csv file? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have some invalid characters in my file that I'm trying to remove. But I ran into a strange problem with one of them.
When I try to use the replace function then I'm getting an error SyntaxError: EOL while scanning string literal.
I found that I was dealing with \x1d which is a group separator. I have this code to remove it:
import pandas as pd
df = pd.read_csv('C:/Users/tkp/Desktop/Holdings_Download/dws/example.csv',index_col=False, sep=';', encoding='utf-8')
print(df['col'][0])
df = df['col'][0].encode("utf-8").replace(b"\x1d", b"").decode()
df = pd.DataFrame([x.split(';') for x in df.split('\n')])
print(df[0][0])
Output:
Is there another way to do this? Because it seems to me that I couldn't do it any worse this.
Notice that you are getting a SyntaxError. This means that Python never gets as far as actually running your program, because it can't figure out what the program is!
To be honest, I'm not quite sure why this happens in this case, but using "exotic" characters in string constants is always a bit iffy, because it makes you dependent on what the character encoding of the source code is, and puts you at the mercy of all sorts of buggy editors. Therefore, I would recommend using the '\uXXXX' syntax to explicitly write the Unicode number for the character you wish to replace. (It looks like what you have here is U+2194 DOUBLE ARROW, so '\u2194' should do it.)
Having said that, I would first verify that this is actually the problem, by changing the '↔' bit to something more mundane, like 'x' and seeing whether that causes the same error. If it does, then your problem is somewhere else...
You have to specify the encoding for which this character is defined in the charset.
df = df.replace('#', '', encoding='utf-8')

SyntaxError: Invalid Syntax without solution [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
It's my first request here, I hope you'll could help me.
I try to explain this particular situation.
Files that use are bases for launch a neuronal simulation and they were for Python 2. Using an Atom's plug-in, I fixed manually any Indent errors and details.
But for this error I can't find a solution.
Traceback (most recent call last):
File "./protocols/01_no_channels_ais.py", line 4, in <module>
from Purkinje import Purkinje
File "/Users/simonet/Desktop/purkinjecell/Purkinje.py", line 202
listgmax = []
^
SyntaxError: invalid syntax
From file Purkinje
self.subsets_cm = np.genfromtxt("ModelViewParmSubset_cm.txt")
for cm in self.subsets_cm:
for d in self.ModelViewParmSubset[int(cm[0])]:
d.cm = cm[1] * 0.77/1.64
self.dend[138].cm = 8.58298 * 0.77/1.64
self.subsets_paraextra = np.genfromtxt("modelsubsetextra.txt", dtype=[('modelviewsubset','f8'),('channel','S5'),('channel2','S5'),('value','f8')])
for para in self.subsets_paraextra:
for d in self.ModelViewParmSubset[int(para[0])]:
d.insert(para[1])
exec('d.gmax_'+para[2]+' = '+str(para[3])
listgmax = [] ############ PROBLEM WOULD BE HERE ##############
for d in self.ModelViewParmSubset[2]:
d.gmax_Leak = d.gmax_Leak/2
self.dend[138].insert('Leak')
self.dend[138].gmax_Leak = 1.74451E-4 / 2
"listgmax" is a unique term in this code. I can't understand where is the problem.
If I delete it, the problem continue in the next line with the same error of Sintax.
Can you help me?
Thanks a lot for your time.
Hope I was clear.
The error is simple, you forgot the closing brackets on the line above, so just say:
exec('d.gmax_'+para[2]+' = '+str(para[3]))
This should fix the errors. Keep in mind for such SyntaxError: invalid syntax the problem mostly is you missing to close brackets or something.
If any doubts or errors, do let me know
Cheers
You're missing a closing parenthesis in the line prior. It should be:
exec('d.gmax_' + para[2] + ' = ' + str(para[3]))
The Python interpreter is reporting the error on the next line because that's the soonest it can tell you didn't just continue the same expression there. In general, with syntax errors, good to look above if you don't find the error exactly where reported.

IndentationError in a Python exercise [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am a beginner so I am sure this is mundane. I am following a beginner's exercise and I typed the code correctly and check and recheck the copy I typed but it doesn't look like what the exercise should look like. Two lines should appear in the output, but only one of them appears. I will include what I type in Atom below and what the code should look like. I am working at following "Learn Python the Hard Way" and this is one of the exercises. I am using a Macbook with Atom as my editor. Notice how only one of the sentences appears in my finished results?
The code I entered in Atom:
# A comment, this is so you can read your program later.
# Anything after the # is ignored by python.
print "I could have code like this." # and the coment after is ignored
# You can also use a comment to "disable" or comment out a piece of code:
# print "This won't run."
print "This will run."
What the code should do if written properly:
$ python ex2.py
I could have code like this.
This will run.
This is what I see when I go to my terminal:
IndentationError: unexpected indent
Renays-MacBook-Pro:mystuff3 renayjohnson$ python ex2.py
File "ex2.py", line 9
print "This will run."
^
IndentationError: unexpected indent
Renays-MacBook-Pro:mystuff3 renayjohnson$
At line 9, the print line is indented with a space. Just remove that space character and rerun your script. Also, looking at the original source of your exercise, there is no indentation in that line. It's worth-mentioning that comment lines are indented at the same level of the code that follows them. In your code at line 7, the block comment line shouldn't be indented as well but it isn't raising any error in that comment line.
However, you should read about the Off-side rule and how such programming languages are expressed by their indentation.

Categories

Resources