Following in my code in Python 3.5
one=[]
dict={}
for i in range(int(input())):
for j in range(9):
one.append(int(input()) #missing one ) <- Line 5
dict[1]='hello' # Line 7
print(dict)
And following is exception thrown.
I have left out a ) on Line 5, but error is shown to be on Line 7.
Is this a bug or there is explanation for showing error on wrong line no ?
The parser doesn't know (and really, cannot know) that you forgot the closing ). It only knows that after skipping the whitespace, it did not expect to find an identifier (dict, in this case) immediately following int(input()). You would get basically the same error message from the more obvious error
>>> one.append(int("3") dict[1]=3)
File "<stdin>", line 1
one.append(int("3") dict[1]=3)
^
SyntaxError: invalid syntax
The similar code
for i in range(int(input())):
for j in range(9):
one.append(int(input())
+ dict[1])
would be fine, since indentation is flexible inside the unclosed parentheses. The parser isn't responsible for guessing which parentheses might be accidentally left open; it just reports where it first finds something that isn't grammatically valid in the current context.
Related
I want to make a list (a_red_total) to store how many times 'David' appears for each iteration in a loop. So if the loop iterates for 4, a_red_total should be like [1,3,3,2...]. However, now it just come up like [1] (I am not sure it just doesn't update or replace the previous value as I know David appears 1 time in loop of 4, so it is the same value either not updating or replacing)
for index, row in end_result.iterrows():
if row['xmax'] < image_width/2:
if row['name'] == 'David':
a_red.append(row['name'])
a_red_row = len(a_red)
a_red_total.append(a_red_row)
I try to move a_red_total.append(a_red_row) one indent forward as followed but i get an error
for index, row in end_result.iterrows():
if row['xmax'] < image_width/2:
if row['name'] in result_list:
a_result = row['name']
if row['name'] == 'level1':
a_red.append(row['name'])
a_red_row = len(a_red)
a_red_total.append(a_red_row)
inconsistent use of tabs and spaces in indentation (, line 68)
Traceback (most recent call last): File "", line 68
a_red_total.append(a_red_row)
^ TabError: inconsistent use of tabs and spaces in indentation
I try to move "a_red_total.append(a_red_row)" for different indent positions but all I get indent error except the current position which seems not right to me.
>>> while True:
... line = input('> ')
... if line == 'done' :
... break
... print(line)
... print( 'Done!' )
File "<stdin>", line 6
print( 'Done!' )
^^^^^
SyntaxError: invalid syntax**
For python 3 this code should give me a "Done!" response when the break statement "done" is reached. However, I keep getting a syntax error for the last line. I have tried to do it multiple ways and I can get the break order to work without the last statement, however, it never works where I include the last statement "print('Done!')" with the break statement done. I apologize, this is just simple code but I can't seem to get it to work. Ps, I fixed it to make it as I am supposed to be writing it, the while True statement was not supposed to be twice (my error in copying it here) along with the extra space on the fifth line. and I have tried
It's not the language, it's your IDE. It is only expecting a single statement and the lines that are subordinate to it, i.e. indented. Once you've reached the end of the indenting it expects a blank line and doesn't know what to do when you try to give another statement.
If that same sequence were part of a file it would do exactly what you expect. If you put it all into a function, the whole function body will be indented and that would work too.
Python has repeatedly been giving me these invalid syntax errors, followed by unexpected indent errors, when I believe my code is correct. I have checked many times for things like tabs vs. spaces so I'm lead to believe its something I don't know about yet that could be going wrong, since I'm also fairly new to python.
Heres my code
def removeDups(L1,L2):
for i in L2[:]:
if i in L1:
L2.remove(i)
I'm sure its a simple fix but I've been trying to figure it out for a while to no avail so if anyone can help thank you.
Also here are the errors I get
File "<stdin>", line 5
def removeDups(L1,L2):
^
SyntaxError: invalid syntax
>>> L2.remove(i)
File "<stdin>", line 1
for i in L2:
^
IndentationError: unexpected indent
>>> def removeDups(L1,L2):
File "<stdin>", line 1
if i in L1:
^
IndentationError: unexpected indent
>>> for i in L2:
File "<stdin>", line 1
L2.remove(i)
^
This code works when I try it from a .py file, but fails in the command line interpreter and Idle.
>>> try:
... fsock = open("/bla")
... except IOError:
... print "Caught"
... print "continue"
File "<stdin>", line 5
print "continue"
^
SyntaxError: invalid syntax
I'm using python 2.6
With Python 3, print is a function and not a statement, so you would need parentheses around the arguments, as in print("continue"), if you were using Python 3.
The caret, however, is pointing to an earlier position than it would be with Python 3, so you must be using Python 2.x instead. In this case, the error is because you are entering this in the interactive interpreter, and it needs a little "help" to figure out what you are trying to tell it. Enter a blank line after the previous block, so that it can decipher the indentation properly, as in this:
>>> try:
... fsock = open("/bla")
... except IOError:
... print "Caught"
...
(some output shows here)
>>> print "continue"
You need to leave a blank line to close the except block. The ... indicates it is still trying to put code in that block, even though you dedent it. This is just a quirk of the interactive interpreter.
Try this one in the interpreter:
try:
fsock = open("/bla")
except IOError:
print "Caught"
print "continue"
Important here is the empty line after the indentation. I'm using the python 2.6 interpreter and it throws the same Syntax error as you.
This is because the interpreter expects single blocks separated by blank lines. Additionally the blank line (two new line characters) indicates the end of the block and that the interpreter should execute it.
Like if/else or for or while, try/except is a compound statement. In a Python shell prompt, statements after control keywords: ... need to be indented because the statement or compound statement is executed one by one. Your last print("continue") is aligned with the top-level try: and considered another statement hence syntax error.
If you want to test out try/except/else/finally interactively, you can wrap them in a function:
>>> def t():
... try:
... print(x)
... except:
... print('exception')
... return
... finally:
... print('finally')
... print('continue')
... print('end function t()')
...
>>> t()
exception
finally
>>> x = 99
>>> t()
99
finally
continue
end function t()
>>>
This was done with Windows python shell. When I tried on PyCharm IDE python console, it allows one more statement after the compound statement to execute.
>>> n = 0
>>> while n!= 5:
... n+=1
... print('n = {}'.format(n))
n = 5 # no syntax error
>>>
I have tried to understand this by looking in previous threads but I still don't understand why I get this error for only one of two variables in the following piece of code (the code sucks I know):
alfaphet=('abcdefghijklmnopqrstuvxyz')
cryptalfaphet=('defghjiklmnopqrstuvxyzabc')
spaceNumber=[]
textCopy=[]
def crypt():
textCopy=[]
print('print the text that you want to encrypt:')
text=input()
for i in range(len(text)):
for j in range(len(alfaphet)):
if text[i]==alfaphet[j]:
textCopy.append(cryptalfaphet[j])
if text[i]==' ':
spaceNumber.append(i)
for i in range(len(spaceNumber)):
for j in range(len(text)):
if list(range(len(text)))[j]==int(spaceNumber[i]):
textCopy.insert(j, ' ')
textCopy=''.join(textCopy)
print(textCopy)
crypt()
This code works fine, but if I remove the
textCopy=[]
asignment from the beginning of the def-block, I get an error like this:
Traceback (most recent call last):
File "C:/Python33/dekrypt.py", line 26, in <module>
crypt()
File "C:/Python33/dekrypt.py", line 13, in crypt
textCopy.append(cryptalfaphet[j])
UnboundLocalError: local variable 'textCopy' referenced before assignment
My question is why this doesn't happen with the spaceNumber variable. spaceNumber is as far I can see also referenced before asignment with the
spaceNumber.append(i)
asignment? It is referenced before the def-block, but so was the textCopy vaiable right? What is the difference, they're both empty lists from the beginning and I use the .append() method on both, but Python seems to treat them differently!?
You can avoid this error by adding the following line at beginning of your function
def crypt():
global textCopy
...
however, this isn't a python best practice. See this post for further details.