Syntax error in Python IDLE (Mac OS X) because of indentation - python

I'm assuming this is going to be stupidly easy to answer, yet I've searched all over and can't find an answer. I'm learning Python and trying to run some very simple code, but I keep getting a syntax error any time I try to do something after an indented block. For example:
x = [1,2,3];
for i in x:
print(i);
print('finished');
When I run this code, I get a syntax error on the print('finished') part. Any time I try to run anything by unindenting after a block like a loop or if statement, I get this error. I'm running Python 3.2.3 in IDLE on Mac OS X Lion.
UPDATE: seems this wasn't as easy as I thought and maybe I'm trying to get something to work that is pointless. I guess the shell only runs multiline statements when you're running a block that indents, but the moment you get back to the top level it executes the statements. Since I'll usually be working with files, most likely in Django, won't matter in the end. Thanks for all the amazingly fast responses though.

At least the python interactive interpreter on my Ubuntu system requires a newline to end the block:
>>> x = [1,2,3];
>>> for i in x:
... print(i);
... print('finished');
File "<stdin>", line 3
print('finished');
^
SyntaxError: invalid syntax
>>> x = [1,2,3];
>>> for i in x:
... print(i);
...
1
2
3
>>> print('finished');
finished
Funny enough, the python interpreter does not require the blank line when run on scripts:
$ cat broken.py
#!/usr/bin/python
x = [1,2,3];
for i in x:
print(i);
print('finished');
$ ./broken.py
1
2
3
finished
$

Take out all your semicolons.
x = [1,2,3]
for i in x:
print(i)
print('finished')

Insert a newline after print(i) (also on windows)
x = [1, 2, 3]
for i in x:
print(i)
print('finished')

Are you trying to enter this code in IDLE's default Python Shell window? You are better off opening an IDLE editor window (menu item File -> New Window) and running the code from there (menu item Run -> Run Module). Indenting in the shell window can get confusing and it is difficult to correct mistakes.

Related

Python3 If Else statement SyntaxError and IndentationError [duplicate]

I am a newbie trying to use Python (2.17.15 via Anaconda) on Visual Stodio Code on my Mac. I have the following simple code:
def function(x):
y = x + 2
return y
This code is giving me the usual trouble, an indentation error:
return y
^
IndentationError: unexpected indent
>>> return y
File "<stdin>", line 1
return y
^
IndentationError: unexpected indent
>>>
Needless to say that Jupyter or Spyder have no problem with this. I checked that on VSC tab gives 4 spaces. All similar questions are related to this, but I cannot fix it.
Other, built in functions of Python work fine.
Please give me some help or tips since I do not know how to escape this.
UPDATE
Installing again Python3 this simple code DOES work on Sublime but still not on VS Code. I still get the same error in VS Code.
UPDATE2
So, another update. If I change from return to print and instead of shift-command debug and run the code then it works.
Any idea what is going on?
This looks like it's because you're running the code with Shift+ENTER.
VS Code has the following 2 bindings for Shift_ENTER:
I believe that you're seeing the 2nd of these, which says "Run Selection/Line in Python Terminal. I suspect you have the focus on the return y line, and so it's only running that single line of code.
If, instead of Shift+ENTER, you use the Run Code command in VS Code, you should see it work fine:
You might well think "OK...so if I select all of the code this will work, right?" and I agree...this feels like it should work. However, I see a similar issue. I'll see if I can work out why, but for the moment you can use the Run Code command in VS Code and that will do what you want. If you highlight the code you want to run, that will limit what gets executed.
Run Code can be executed with Ctrl+Alt+N
It looks like this issue (that selected code doesn't run correctly with Shift+ENTER) is a bug that's being tracked by here: https://github.com/Microsoft/vscode-python/issues/2837
And a work around (not ideal) is to add code before/after your function that is NOT indented, and then select and execute those lines too:
print("this...")
def function(x):
y = x + 2
return y
print("...now works if you select all these lines and Shift+ENTER!")
This is a bug from the python extension, which you need to run chunks of code in the interactive mode.
So in the example code below:
for lastRun in list(d_RunPanelsPresent.keys()):
# some indented commands
logFile = f"/nexusb/Novaseq/{lastRun}/logPPscript.txt"
if not os.path.isfile(logFile):
with open(logFile, 'w+') as f:
pass
else:
pass
If I highlight as follows (note where the cursor is):
I will get an error.
The solution is to highlight the code from the very left of the code editor, as shown below:
This works for me 100% of the time.
Forgetting a semicolon at the end of the function definition produces the same error.

There is a problem when I use indentation in Python

def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
This is a basic example for defining a function, and when I run this code on Python 3.8.5 by VSC, the result is like below.
>>> def greet(name):
...
File "<stdin>", line 2
^
IndentationError: expected an indented block
It says that there is an indentation error but I really don't know why. And also, line 2 is not just blank but according to the result, line 2 seems like blank.
for number in range(5):
print("Thank you")
>>> for number in range(5):
...
File "<stdin>", line 2
^
IndentationError: expected an indented block
Same error for 'for'. Can anyone help?
Right now, you are running the Python script line-by-line by placing the VS Code cursor on each line of code and then pressing shift+enter. This utilizes the Python Interactive window afaik. It works fine for running individual lines but if you want to run a collection of lines that include indentation e.g. a for loop or function definition, then select all of those lines together and then press shift+enter. You would need to do this for code that's indented, for example:
def greet(name):
print("Hello, " + name + ". Good morning!")
Alternatively, if you have read Getting Started with Python in VS Code and specifically installed the Python extension for VS Code then you will be able to click the Run Python File in Terminal button (it looks like a Play icon) to run your Python script.
Alternatively, you can launch a Terminal Window in VS Code and manually run the Python script using python3 hello.py (or potentially python hello.py, depending on your Python installation).
You should not press Shift+Enter to run the code in the terminal line by line.
Because the REPL will add an Enter to start a new line automatically like this:
You can select all of the codes then send them to the REPL:

Indentation error on Visual Studio Code on a Mac (again)

I am a newbie trying to use Python (2.17.15 via Anaconda) on Visual Stodio Code on my Mac. I have the following simple code:
def function(x):
y = x + 2
return y
This code is giving me the usual trouble, an indentation error:
return y
^
IndentationError: unexpected indent
>>> return y
File "<stdin>", line 1
return y
^
IndentationError: unexpected indent
>>>
Needless to say that Jupyter or Spyder have no problem with this. I checked that on VSC tab gives 4 spaces. All similar questions are related to this, but I cannot fix it.
Other, built in functions of Python work fine.
Please give me some help or tips since I do not know how to escape this.
UPDATE
Installing again Python3 this simple code DOES work on Sublime but still not on VS Code. I still get the same error in VS Code.
UPDATE2
So, another update. If I change from return to print and instead of shift-command debug and run the code then it works.
Any idea what is going on?
This looks like it's because you're running the code with Shift+ENTER.
VS Code has the following 2 bindings for Shift_ENTER:
I believe that you're seeing the 2nd of these, which says "Run Selection/Line in Python Terminal. I suspect you have the focus on the return y line, and so it's only running that single line of code.
If, instead of Shift+ENTER, you use the Run Code command in VS Code, you should see it work fine:
You might well think "OK...so if I select all of the code this will work, right?" and I agree...this feels like it should work. However, I see a similar issue. I'll see if I can work out why, but for the moment you can use the Run Code command in VS Code and that will do what you want. If you highlight the code you want to run, that will limit what gets executed.
Run Code can be executed with Ctrl+Alt+N
It looks like this issue (that selected code doesn't run correctly with Shift+ENTER) is a bug that's being tracked by here: https://github.com/Microsoft/vscode-python/issues/2837
And a work around (not ideal) is to add code before/after your function that is NOT indented, and then select and execute those lines too:
print("this...")
def function(x):
y = x + 2
return y
print("...now works if you select all these lines and Shift+ENTER!")
This is a bug from the python extension, which you need to run chunks of code in the interactive mode.
So in the example code below:
for lastRun in list(d_RunPanelsPresent.keys()):
# some indented commands
logFile = f"/nexusb/Novaseq/{lastRun}/logPPscript.txt"
if not os.path.isfile(logFile):
with open(logFile, 'w+') as f:
pass
else:
pass
If I highlight as follows (note where the cursor is):
I will get an error.
The solution is to highlight the code from the very left of the code editor, as shown below:
This works for me 100% of the time.
Forgetting a semicolon at the end of the function definition produces the same error.

Can't run a python program in terminal? [Mac OSX]

I'm trying to execute a python program from Terminal but it isn't working.
Something like:
x = 5
Then typing:
UserName:Documents UserName$ python simple.py
Outputs:
UserName:Documents UserName$
Without actually executing/opening the file.
But if I have a program like:
x = input('Something: ')
Then it shows up in terminal, such as:
UserName:Documents UserName$ python simple.py
Something:
Probably a silly question, but been trying to fix it for the last 1.5 hours and can't find a workable solution.
The short program
x = 5
gets run and then Python exits back to the command line. No problem there, it all works correctly. If you want to stay inside the interpreter, start your program with
python -i simple.py
When running that, you will get the usual interpreter prompt after it is finished:
>>>
and you can see it did run, because x got the expected value:
>>> x
5
>>> x*x*x*x/(x+x+x-x/x)-x/x-x/x
42
Also, from inside the interpreter, you can load-and-run your file again:
>>> execfile('simple.py')
>>> x
5
See Bojan Nikolic's Running Python Programs from the Command-line for a number of other startup options.
It looks like it is working exactly as written... but maybe not as intended... The input prompt asks you to enter a value...
maybe you want to add a print so that you get a feedback that your program does something:
x = input('Something: ')
print(x)
if you are using python 2.x:
x = raw_input('Something: ')
print x
Then, on the prompt, input a value and press enter

Python Use of File = defined variable

I am attempting to output a file that was read and altered.
new_file = open("MC_QS_MODIFIED.inp","w")
...
...
print( final_data , file=new_file )
new_file.close()
and python is taking exception to the = in print(final_data, file=new_file )
It worked at home but now that I am attempting to run the script at work, Python 2.7.6 is giving me a syntax error. I am still pretty new to this, so I don't know if my code is 3.0+ and 2.7.6 doesn't like it or what.
In Python 2, print() is not a function but a statement, unless you tell Python you want to use the Python 3 syntax.
Put this at the top of your file:
from __future__ import print_function
to disable the print statement in the compiler so you can use the print() function instead.
You may run into other problems if you developed on Python 3 and try to run on Python 2, however.

Categories