Unexpected Indent Error at End of File - python

For some reason at the end of of my python file in IDLE I'm getting an indentation error, even though the block of code has the right amount of spacing. Also when I try to run and am told about the error, it actually highlights the whole line after the code, instead of highlighting the character before a line of wrongly indented code, as it normally does.
Here's a screenshot demonstrating where it highlights:
For reference, this is how looks when highlighting a clearly real indent problem:
The code itself has problems with this form:
if yes.lower() == 'y': linkFiles(folders)
raw_input(iprint('= Script Finished, press enter to quit.',True))
and this form:
if yes.lower() == 'y':
linkFiles(folders)
raw_input(iprint('= Script Finished, press enter to quit.',True))
Also yes, I have confirmed that I'm not mixing tabs and spaces. Just using spaces on all these lines.
I also checked about any whitespace at the end of the file, but this error occurs the same even when there's no characters whatsoever after the closing bracket. And attempting to run the script does add a newline character, but nothing else.
As per a suggestion, I did try to run it through the commandline and got essentially the same result:
C:\Windows\system32>python "C:\Users\ntreanor\Desktop\User Friendly Scripts\Create file links.py"
File "C:\Users\ntreanor\Desktop\User Friendly Scripts\Create file links.py", line 135
^
IndentationError: unexpected unindent

This was actually way more simple than I had thought.
I was writing a try: except: block over the whole script, basically because I'm writing to a log and I want it to spit out any exceptions I get into the log so that I can troubleshoot after the fact when people have used my script. The details of this are from another question here
The problem was I got interrupted when writing the script and forgot I had added the try but not the except. So the actual error was that I was missing the whole except block. Once I even just added
except: pass
at the end, it ran fine.

Related

Python: What Does This Syntax Error Mean? [duplicate]

I think this is perfectly valid.
if False:
print(1)
print(2)
However, it gives me an invalid syntax error in Python REPL.
Why is it?
On Python 3.6.5 (x64), Windows 10 RS4
As pointed out by user2357112, this behaviour is explained in https://docs.python.org/3/tutorial/introduction.html#first-steps-towards-programming,
The body of the loop is indented: indentation is Python’s way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.
The REPL can only read and evaluate one statement at a time.
You entered two statements at once.
This is possible because the REPL cannot decide if the third line is going to continue the if construction or start a whole new statement. It has to assume the former to allow indented blocks at all.
You have to make it clear to the REPL that your previous statement is finished before starting a new one.
Wrong version seems to be the most possible since, in the error it shows print. In the older python versions, print was used as print"ok", I see your operating system is windows so you can just directly download python3 from https://python.org/ have a nice day!

What is this error message, and how do I resolve it?

I'm taking google's python tutorial and may have fat fingered a few keys, causing an error. I don't recognize the issue here, and the ctrl+click links it allows me to follow take me to line 1 of the file I'm writing in and to python.exe.
It looks like there's an extra character somewhere in a file path? There are no syntax errors in the code itself as the debugger runs through it just fine.
I'm using Visual Studio Code
None of the code I've written (with my knowledge) is causing this error.
This is the error message I'm getting.
SyntaxError: invalid syntax
>>> & C:/Users/mcgilm1/AppData/Local/Programs/Python/Python37-32/python.exe c:/Users/mcgilm1/Documents/google-python-exercises/basic/string2.py
File "<stdin>", line 1
& C:/Users/mcgilm1/AppData/Local/Programs/Python/Python37-32/python.exe c:/Users/mcgilm1/Documents/google-python-exercises/basic/string2.py
^
Including your code could help us, here is a list of things to check that I found on the web: Debugging
Make sure you are not using a Python keyword for a variable name.
Check that you have a colon at the end of the header of every compound statement, including for, while, if, and def statements.
Check that indentation is consistent. You may indent with either spaces or tabs but it’s best not to mix them. Each level should be nested the same amount.
Make sure that any strings in the code have matching quotation marks.
If you have multiline strings with triple quotes (single or double), make sure you have terminated the string properly. An unterminated string may cause an invalid token error at the end of your program, or it may treat the following part of the program as a string until it comes to the next string. In the second case, it might not produce an error message at all!
An unclosed bracket – (, {, or [ – makes Python continue with the next line as part of the current statement. Generally, an error occurs almost immediately in the next line.
Check for the classic = instead of == inside a conditional.

Why am I getting an invalid syntax error in Python REPL right after IF statement?

I think this is perfectly valid.
if False:
print(1)
print(2)
However, it gives me an invalid syntax error in Python REPL.
Why is it?
On Python 3.6.5 (x64), Windows 10 RS4
As pointed out by user2357112, this behaviour is explained in https://docs.python.org/3/tutorial/introduction.html#first-steps-towards-programming,
The body of the loop is indented: indentation is Python’s way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.
The REPL can only read and evaluate one statement at a time.
You entered two statements at once.
This is possible because the REPL cannot decide if the third line is going to continue the if construction or start a whole new statement. It has to assume the former to allow indented blocks at all.
You have to make it clear to the REPL that your previous statement is finished before starting a new one.
Wrong version seems to be the most possible since, in the error it shows print. In the older python versions, print was used as print"ok", I see your operating system is windows so you can just directly download python3 from https://python.org/ have a nice day!

Auto correct indentation errors in Python

I am trying fix some indentation errors in a Python script. Is there a way to auto correct the errors online or using other utilities?
I hope this error is very familiar, but wanted to avoid this again. Does any editor help in fixing these issues?
IndentationError: expected an indented block
It's not possible in general because some cases would be ambiguous:
something = foo()
if something:
something.bar()
print("ok") # Only half indented. Should this be inside or outside of the if statement?
It's much better to find an editor with auto-indentation support and make sure you indent properly (even in languages without significant whitespaces, as it makes your code easier to read).
You can use reindent.py
For me it worked on some files but it didin't work on others.Give it a try.
reindent.py
Uasge:
reindent.py <filename>.py
Change Python (.py) files to use 4-space indents and no hard tab characters.
Also trim excess spaces and tabs from ends of lines, and remove empty lines
at the end of files.
You can use Spyder IDE
Source Menu -> Fix Indentation
This particular error usually occurs when you forget to add an indented block after a statement that needs one (i.e. if or for). You likely forgot to indent the required block or accidentally hit backspace (or something) such as
def sayhello():
print "Hello world!"
Sometimes you don't want any code after an if statement or after try/except statements, but python will require at least one line after them, so you can use the pass keyword
try:
x= 4/0
except:
pass
print x

vim highlighting everything in red

I added a print line to a python script while the script was executing, and now all the text is highlighted in red when I open the file. Opening and closing the file doesn't get rid of it. Opening a second python file momentarily fixed the problem, but then closing file and reopening brought the problem back. Now it wont go away at all. Any body know what could cause this?
This happens sometimes in vim when it goes to highlight syntax on multi-line comments. Occasionally everything after the multi-line comment also becomes colored the same as the comment.
I am unsure whether this is a legit bug in vim, or in the actual syntax settings for Python (e.g. python.vim), but I definitely experience this from time-to-time.
For a quick fix, you might try typing:
:hi Error NONE
And then hit Enter.
Old thread, but hope this helps.
By mistake I did a "/." on my vim screen, which highlighted all lines in red. If I open any other file, the red highlighting stays.
Try searching for some other keyword, let's say "/word" - doesn't matter word exists or not. It restores the color.
You probably have an unterminated multiline string. They start and end with either three single or three double quotes.
''' <== this is the start of a multiline string
this is still in the string
this is the last line '''
As per this article http://vim.wikia.com/wiki/Fix_syntax_highlighting, I mapped F12 to resync the syntax highlighting from the start of the file. It has worked better in some instances where <ctrl-l> didn't.
noremap <F12> <Esc>:syntax sync fromstart<CR>
inoremap <F12> <C-o>:syntax sync fromstart<CR>

Categories

Resources