Reputation: 43
There are a lot of questions concerning indentation errors on stack overflow and I've been through a lot. But the solutions that have worked there were to either include a tab (or 4 spaces) in the following line, or else fix other issues there were with the more complex code, which answers don't work or don't seem applicable in my case.
The problem I'm having is that code will run when I have it all on one line. But when I include an enter
and a tab
stroke, the interpreter throws an indentation error.
The simplest example that generates the error is (using 4 spaces here):
if 3 + 5 > 0:
print("8")
I'm using Spyder as an IDE and it indents it for me, but whether I use Spyder's indent or indent it myself (with tab or 4 spaces), the error I get is:
In[20] if 8 + 4 > 0:
File "C:\Users\..\AppData\Local\Temp\ipykernel_9452\858389318.py", line 1
if 8 + 4 > 0:
^
IndentationError: expected an indented block
If I write the same code on the same line, I don't get an error.
if 3 + 5 > 0: print("8")
8
No matter which code I type, the Indentation Error is always just at the end of the colon when I indent, and disappears when I write it all on the same line.
As another example, in the below code (again using 4 spaces here):
def iris_data():
print("hello")
I get the error:
In [22]: def iris_data():
File "C:\Users\..\AppData\Local\Temp\ipykernel_9452\1971884337.py", line 1
def iris_data():
^
IndentationError: expected an indented block
Whereas if I write it on the same line, the error disappears:
def iris_data(): print("hello")
iris_data()
hello
And again in the following example:
for i in range(1,11):
print(i)
I get the error:
for i in range(1,11):
File "C:\Users\..\AppData\Local\Temp\ipykernel_9452\1334445784.py", line 1
for i in range(1,11):
^
IndentationError: expected an indented block
Whereas if I type it on the same line:
for i in range(1,11): print(i)
1
2
..
I thought maybe I was mixing spaces (behind the colon) with tabs (on the following line), but I get the same error when I don't insert a space behind the colon (just a tab on the following line). I get the same error when I just let the IDE do it's job and automatically format the spacing for me after the enter
strokes. Also, highlighting the code and going to Source -> Fix Indentation doesn't help, I get the same error.
It seems as though it's the enter
that's causing the error, but this seems rather hard to fathom.
I'd be very grateful for any help or pointers.
Upvotes: 0
Views: 246
Reputation: 43
I was running only the line by putting the cursor in/on it and pressing F9
.
What I wanted to do was run the cell by pressing ctrl
+ return
.
It's such a stupid mistake that I couldn't find anything on Google or Stack Overflow.
Hope this maybe helps out another absolute beginner.
(Much gratitude to the legendary Carlos Cordoba for taking time to answer such an elementary problem.)
Upvotes: 1