Invalid Syntax error in Python Code I copied from the Internet - python

One of my early courses in the University I attend, was some basic training in Python 3 years ago. Now I was looking for a program that could help me resize some Grid stuff and I found something that could help me in Python. I reinstalled Python to my PC and found my old editor. However when I run the code I get an invalid syntax error that I can't understand. This is the part of the code that the error appears in :
def downsize(mode, cell_size, inpath, outpath):
from VolumeData import fileformats
try:
grid_data = fileformats.open_file(inpath)
except fileformats.Uknown_File_Type, e:
sys.stderr.write(str(e))
sys.exit(1)
reduced = Reduced_Grid(grid_data, mode, cell_size)
from VolumeData.netcdf.netcdf_grid import write_grid_as_netcdf
write_grid_as_netcdf(reduced, outpath)
The exact invalid syntax error is in the "except fileformats.Uknown_File_Type, e:" line. Can you help me ?

If you are using Python 3.x, you cannot use except fileformats.Uknown_File_Type, e. The comma works as an as statement (in the try/except block), so you should replace it with: except fileformats.Uknown_File_Type as e.
The comma works in Python 2.7, but not 3.x. However, the as should work for both.
Reference: Handling errors in Python 3.3

Maybe you misspelled 'Unknown'?

Related

Python3 : EOF Error while taking input on GUVI

This is my code in python3:
import heapq
myQueue = []
n = raw_input()
try:
num = int(n)
if num<=100000 :
arr = input().split()
for i in range(num):
heapq.heappush(myQueue, arr[i])
print(myQueue[0])
except (NameError, ValueError):
print("Wrong Input, N should be under 100000")
except IndexError:
print("Inputs is less than actually required")
except EOFError:
print ("Error: EOF or empty input!")
I am trying to implement priority queue.
But I am facing this EOF Error while solving this problem on GUVI.
Output:
Error: EOF or empty input!
The tried to catch the error using except EOFError, but that will just make my program run but does not solve input problem right.
I even tried to run this piece of code on Sublime text editor as well as Vs code,
where it runs just fine, Correct Output.
I don't understand, is there a problem in my code or That Online Platform.
I even tried to search the answer on their Q&A platform of GUVI, I found similar question but no one has answered it.
And this is not just for this piece of Code but I found the same error for many before.
Could ANYONE help me, Please!
Thanking you in advance.. :)
EOF error occurs if the input is not provided.
In case of most of the online compilers you need to provide the inputs before running the code.
With that said, while your are trying to access the input via raw_input() there will be no input supplied resulting in the above error.
To avoid this, error supply inputs before running your code like below
Also, I can notice that you are using raw_input() and input(). Please note that raw_input() can be used if you are using Python 2 and input() if you are using python 3 correspondingly.

Learn Python the Hard Way - EX 41 - Invalid Syntax

I keep receiving SyntaxError message on ex41.py OR oop_test.py, and I've run through the whole script, everything is exactly as it is in the book, but I keep getting this - the variable {answer} is seemingly only defined in the try: section, so I have no clue why I am getting this SyntaxError.
***:hardway ***$ python ex41.py english
File "ex41.py", line 76
print(f"ANSWER: {answer}\n\n")
^
SyntaxError: invalid syntax
Here is the try: section, where the variable is at:
try:
while True:
snippets = list(PHRASES.keys())
random.shuffle(snippets)
for snippet in snippets:
phrase = PHRASES[snippet]
question, answer = convert(snippet, phrase)
if PHRASE_FIRST:
question, answer = answer, question
print(question)
input("> ")
print(f"ANSWER: {answer}\n\n")
except EOFError:
print("\nBye") `
The entirety of the code can be found here: Learning Python The hard way Ex. 41 - Learning to Speak Object-Oriented
Your code looks fine. The problem is the Python version you are running.
As mentioned in the comments above f strings were first introduced in Python 3.6 (see official documentation). If you want to use this feature you need to update to Python 3.6.
If you do not (or cannot) switch version you can use format() instead:
print("ANSWER: {}\n\n".format(answer))
OR use the old style %s (formatting string) operator:
print("ANSWER: %s\n\n" %answer)
See: What does %s mean in Python?
I would suggest format() over the second method though.
If you are making code that will be run on Python versions before Python 3.6 it it a good idea to use the alternatives listed above.

What is wrong with this python 3 syntax for printing Conversion error?

OK, I am following a great course on python on Pluralsight. I'm stumped on this syntax error even though I'm staring right at the instructor's code that works fine. It's real short.
import sys
def convert(s):
try:
return int(s)
except (ValueError, TypeError) as e:
print("Conversion error: {}".format(str(e)), file=sys.stderr)
return -1
The instructor used a \ after the error: {}"\ - that's how his code looked, with indents for the .format statement and the file= statement. I've tried that along with a space after the quotation mark and the .format(str(e)) and I keep getting syntax errors when I import it into the REPL. I'm using python 3.3, btw.
Thanks in advance for any tips,
Bruce

Python 3.3: separation argument (sep) giving an error

I am very new to programming and I'm starting out with Python. I tried to look up my question here but didn't really find anything.
I'm trying to work a very simple print command but I'm getting an error for some reason that I don't understand.
last = 'smith'
middle = 'paul'
first = 'john'
print(first.capitalize(), middle.capitalize(), last.capitalize(), sep='\t')
According to the answer in the book, this should be right, but every time I try to run it, I get an error with the 'sep':
print(first.capitalize(), middle.capitalize(), last.capitalize(), sep='\t')
^
SyntaxError: invalid syntax
Can someone tell me what I'm doing wrong. for what it's worth I'm using PyScripter.
[EDIT]
Thanks for that. I found out that I'm using Python 2.7.3 instead of 3.3. So I looked up the manual to see how the separator works. It seems to me that the only difference is with the square bracket. The manual describes the print function as :
print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout])
So I changed my print command and added the square bracket:
print ([first.capitalize(),middle.capitalize(),last.capitalize()] [, sep='\t'])
but unfortunately this doesn't work either as I get an error that highlights the square brackets around sep='\t'. Even when I take the brackets out, the error doesn't go away.
I'm not sure what I'm doing wrong, it seems like it should be very simple.
You aren't actually using Python 3, you just think you are. Try:
import sys
print(sys.version)
and see what comes out. The Python 2 print ... statement (not print(...) function in Python 3) interprets this as
print (first.capitalize(), middle.capitalize(), last.capitalize(), sep='\t')
which is trying to print a tuple with a keyword argument, thus the syntax error on sep

Getting "invalid syntax" from previously working code

So I have the following code:
f = open('input.txt', 'r')
text = f.read()
data = text.split()
print data
print '<HTML>\n <HEAD>\n </HEAD>\n <BODY>\n <table border="1">\n'
for x in data:
print ' <tr>' + x + '<tr>'
print'</table>\n </BODY>\n</HTML>'
before I tried to installed iPython, it was working with the default Python shell.
But after I installed distribute and pyreadline and then iPhython, the code won't stop giving me syntax errors, as if not a single variable would work, not sure if there is something about python initialization/declaration that I have missed or if something went wrong with doing stuff on the console, but it certainly is driving me crazy and I need to fix it.
P.S. I use Windows 8
Edit:
Was asked for the errors I get, here are screenshots, since I do not get any very specific text-like errors.
In this second one, I edited the code several times to test different things,
hence why I get error for different variables.
Even the simplest of things would give me an error.
P.S.2. I just tried print 'hey' and it gave me the same error, not recognizing the ' token.
Looks like whatever you installed is using Python 3.x, and your code was written for Python 2.x.
In Python 3.x, print is now a function, not a keyword, so you'll have to change all the lines like...
print data
...to...
print(data)
If you need to retain Python 2.x compatibility, add the line...
from __future__ import print_function
...at the top of the code.

Categories