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!
Related
Running Jupyter (core:4.4.0, notebooks:5.7.8) python3 notebooks on OSX.
The notebook seems to get easily confused about how to auto-indent new lines. Specifically, my more complex cells that have nested indentations for defs, ifs, whiles (etc) cause Jupyter to use a weird 4.5-tab auto-indent that doesn't match any of my indentation levels and leads to lots of wasted keypresses to fix the indent on EVERY. SINGLE. NEW. LINE.
To be clear, I'm not asking how to change the default tab spacing, I'm asking how to stop jupyter autoindenting to something insane when I hit 'return' to make a new line.
One potential source of error is my use of f-strings; Jupyter sometimes screws up the syntax highlighting for hashes and nested quotes eg. print(f"Output for #{myNum} | {myDict['namedItem']}").
Any tips on what might cause the issue would welcome.
Answer: Yes it is f-string literals. Nested quotations in an f-string will screw up the indentation in cell, setting the new line default to start of the quote in the f-string.
eg.
print(f"Output for #{myNum} | {myDict['namedItem']}")
# Newline starts here
# and here
# Manual de-indent here for readibility.
x=5 # and manually force python code to an indent where it actually runs
# Default newline is still here though
# And will stay here for the rest of the cell
f-strings generically break the CodeMirror syntax highlighter underlying jupyter notebooks, known since Jan 2017. There have been some minor fixes to make it break less badly, but the problem is not fixed -- see recent Git issues
EDIT: Since Jan 2020 jupyter 6.0.2, this should be fixed via an update to CodeMirror 5.48.4.
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!
I recently encountered the common "unexpected indent" problem when trying to evaluate python code by copying them from PyDev and Emacs into a python interpreter.
After trying to fix tab/spaces and some searches, I found the cause in this answer:
This error can also occur when pasting something into the Python
interpreter (terminal/console).
Note that the interpreter interprets an empty line as the end of an
expression, so if you paste in something like
def my_function():
x = 3
y = 7
the interpreter will interpret the empty line before y = 7 as the end
of the expression ...
, which is exactly the case in my situation. And there is also a comment to the answer which points out a solution:
key being that blank lines within the function definition are fine,
but they still must have the initial whitespace since Python
interprets any blank line as the end of the function
But the solution is impractical as I have many empty lines that are problematic for the interpreter. My question is:
Is there a method/tool to automatically insert the right number of initial whitespaces to empty lines so that I can copy-and-paste my code from an editor to an interpreter?
Don't bother with inserting spaces. Tell the interpreter to execute a block of text instead:
>>> exec(r'''
<paste your code>
''')
The r''' ... ''' tripple-quoted string preserves escapes and newlines. Sometimes (though in my experience, rarely) you need to use r""" ... """ instead, when the code block contains tripple-quoted strings using single quotes.
Another option is to switch to using IPython to do your day-to-day testing of pasted code, which handles pasted code with blank lines natively.
Update: The original question was posted using C-RET to run the lines, which produces the error. I get no such error using The menu Python > Eval region, which successfully evaluates the script.
However, using the menu for every execution is really annoying, and moreover I can't run the present line alone with that method. So my problem remains.
Forgive me if I'm missing something obvious, but I can't figure this out.
This code is giving me an IndentationError. I can't imagine what's going on.
for x in range(0, 3):
print "We're on time %d" % (x)
Here's everything related to python in my emacs.el
;; elpy
(add-to-list 'package-archives
'("elpy" . "http://jorgenschaefer.github.io/packages/"))
(package-initialize)
(elpy-enable)
You've mixed tabs and spaces. This can lead to some confusing errors.
I'd suggest using only tabs or only spaces for indentation.
Using only spaces is generally the easier choice. Most editors have an option for automatically converting tabs to spaces. If your editor has this option, turn it on.
You can paste your code in notepad to see.
All commands from menu have a command-name callable via M-x COMMAND RET.
In this case M-x python-send-region RET
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