Invalid syntax after FOR statement - python

I have this piece of code that splits a string with a comma and prints each element:
prefixes="item1,item2,item3"
for prefix in prefixes.split(","):
print prefix
Now, when I try to execute the code above, I get the following error:
Problem invoking WLST - Traceback (innermost last): (no code object) at line 0 File "example.py", line 21
print:
^ SyntaxError: invalid syntax
I tried chaging the code to the following:
prefixes="item1,item2,item3"
for prefix in prefixes.split(","):
try:
print prefix
But then I get the following error:
try:
^ SyntaxError: invalid syntax
This should be very simple but it seems that everything I put after the FOR statement becomes invalid.
Any help would be appreciated. Thanks!

For your particular script you need to put in an except. Unless you're doing something you're not telling us, this will accomplish the print.
prefixes="item1,item2,item3"
for prefix in prefixes.split(","):
try:
print prefix
except:
pass

Related

Invalid Syntax in print

print("inventory[", start,":", finish, "] is", end=" ")
This line of code has my program stuck. It didn't like the spacing so I eliminated it and now it is flagging the colon as invalid syntax. It is straight from my textbook and is a lesson about slicing lists. What am I missing?
For me this code works perfectly if start and finish have been defined.
This error can originate from a SyntaxError in the line before the print. Most certainly you are missing a parens or a bracket.
As an example consider the following code:
print(42 # closing parens intentinally missing here
print(23)
When executed this raises the following error:
File "foo.py", line 2
print(23)
^
SyntaxError: invalid syntax
As you can see the SyntaxError shows one line after the actual error. I suggest you check the line before your print statement.

Python: Invalid Syntax error on a line that doesn't exist

I'm using Notepad ++ to write my code but I keep getting an Invalid Syntax error on a line that doesn't extra.
The code stops at line 54 and it's saying the error is on line 55.
I'm assuming this is a copy and paste related error, but I can't seem to find a way to fix it.
Any suggestions would be great.
Edit - code on line 53 / 54;
city = hashmap.get(cities,'TX', 'Does Not Exist')
print "The city for the state 'TX' is: %s" % city
The error I'm getting is;
File ex38.py, line 55
^
SytanError: invalid sytanx
You forgot to close a set of parentheses, or possibly a multiline string. Or you had a statement that takes a block (like if x:) on the last line and didn't follow it with anything. But most likely the parens. Somewhere there is a ( without a corresponding ).
In the same line you are executing two instructions ,assigning and printing a variable .I think it won't work. Use newline for print statement

Syntax error with exec call in Python

Quick python question about the exec command. I'm have Python 2.7.6 and am trying to make use of the exec to run some code stored in a .txt file. I've run into a syntax error and am not entirely sure what is causing it.
Traceback (most recent call last):
File "/Users/XYZ/Desktop/parser.py", line 46, in <module>
try_code(block)
File "<string>", line 1
x = 'Hello World!'
^
SyntaxError: invalid syntax
I initially thought it was complaining about carriage returns, but when I tried to edit them .replace them with ' ' I still received this error message. I've tried variations to see what appears to be the issue and it always declares the error as the first ' or " the program encounters when it runs exec.
Here is the try_code(block) method
def try_code(block):
exec block
And the main body of the program
inputFile = open('/Users/XYZ/Desktop/test.txt', 'r+')
starter = False
finished = False
check = 1
block = ""
for val in inputFile:
starter = lookForStart(val)
finished = lookForEnd(val)
if lookForStart:
check = 1
elif finished:
try_code(block)
if check == 1:
check = 0
elif finished == False:
block = block + val
Basically I'm trying to import a file (test.txt) and then look for some embedded code in it. To make it easier I surrounded it with indicators, thus starter and finished. Then I concatenate all the hidden code into one string and call try_code on it. Then try_code attempts to execute it (it does make it there, check with print statements) and fails with the Syntax error.
As a note it works fine if I have hidden something like...
x = 5
print x
so whatever the problem is appears to be dealing with strings for some reason.
EDIT
It would appear that textedit includes some extra characters that aren't displayed normally. I rewrote the test file in a different text editor (text wrangler) and it would seem that the characters have disappeared. Thank you all very much for helping me solve my problem, I appreciate it.
It is a character encoding issue. Unless you've explicitly declared character encoding of your Python source code at the top of the file; it is 'ascii' by default on Python 2.
The code that you're trying to execute contains non-ascii quotes:
>>> print b'\xe2\x80\x98Hello World\xe2\x80\x99'.decode('utf-8')
‘Hello World’
To fix it; use ordinary single quotes instead: 'Hello World'.
You can check that block doesn't contain non-ascii characters using decode method: block.decode('ascii') it raises an exception if there are.
A gentle introduction into the topic: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
by Joel Spolsky.

Python keeps generating syntax errors

This line had an error:
print('Already built: ' + str(deletedDirs) + ' servers')
On 't' in the word print.
I deleted this one and then the line below it had a syntax error:
time.sleep(timeToSleep)
On 'e'
And so on.... Help me please. It worked yesterday but today it does not.
The line before the statement is missing a closing parenthesis, or curly or square bracket.
The lines you keep deleting are not the problem, but Python doesn't know this until it discovers that that next line makes no sense when it was looking for a comma or closing parenthesis instead.
Demo; there should be two closing parenthesis:
>>> some_function(str('with additional arg, but missing closing parens')
... print('Oops?')
File "<stdin>", line 2
print('Oops?')
^
SyntaxError: invalid syntax
check the file encoding
check the indents

while loop in python gives syntax error

I am very new to python, this is my first program that I am trying.
This function reads the password from the standard input.
def getPassword() :
passwordArray =[]
while 1:
char = sys.stdin.read(1)
if char == '\\n':
break
passwordArray.append(char)
return passwordArray
print (username)
print (URL)
getting this error:
Problem invoking WLST - Traceback (innermost last):
(no code object) at line 0
File "/scratch/aime/work/stmp/wlstCommand.py", line 10
while 1:
^
SyntaxError: invalid syntax
Your indentation is not correct. Your while should be indented the same as the line above it.
Python uses indentation to "separate" stuff and the thing with that is you need to have the same kind of indentation across the file. Having a fixed kind of indentation in the code you write is good practice. You might want to consider a tab or four spaces(The later being the suggestion in the PEP8 style guide)
Python is sensitive and depended on indentation. If it complains "invalid Format", that is better than "invalid syntax".

Categories