Why am I getting a SyntaxError in the Python interpreter? - python

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
>>>

Related

How can I read lines from a txt file (which contains a code) and decide whether it is correct or not?

The text file contains Python codes.
My task is to write a program which checks if it could run in python. I cannot find out how to check if the lines are correct in python.
I can read lines from the text file, but still don't know how to decide if the current line would run without any error messages. If it would run the program prints True, else False.
lst=[]
with open("be.txt","r") as be:
for line in be:
lst.append(line.strip("\n"))
For example: A line is: "for i in range(8:"
The result should be False, because this ")" is missing.
You can use exec:
with open("be.txt","r") as be:
source = be.read()
try:
exec(source)
print("True")
except Exception as e:
print(e) #this add some info on where the error occurred
print("False")
First create a single string source holding all the code in your file.
Then in a try except block use exec to se if it runs. If it fails anywhere, an exception will be raised, and the except block is executed.
Generally functions like exec or eval are considered dangerous and nasty (see for example here or here) but I think in your case is the simplest thing you can do.
The only way to know whether the code would run in python without any error messages is to execute it. The following would do that. Of course, you would need to go to extra lengths to suppress any output if the program is correct and produces output.
def runner():
with open("be.txt","r") as f:
code = f.read()
try:
exec(code)
except Exception as e:
print("False")
else:
print("True")
runner()
Use exec and catch exceptions. exec will attempt to execute the line as Python code. If it succeeds then the line is executed and any side-effects (eg. the creation of new variables) take place. If not, an exception is thrown and you can skip it and move on to the next line. Something like this:
lst=[]
with open("be.txt","r") as be:
for line in be:
try:
exec(line)
lst.append(line.strip("\n"))
except:
pass
Note this will not work if a single line is not a complete Python statement. Eg. if you have a function def or a for loop over several lines, you'll have to exec them all at once to succeed.

why print statement don't work as intended? [duplicate]

This question already has answers here:
python print done after while
(4 answers)
Closed 7 years ago.
li=['ram', 12, 13, 'shyam']
>>> for i in li:
... print(i)
... print("hi")
File "<stdin>", line 3
print("hi")
^
SyntaxError: invalid syntax
I'm working on Ubuntu shell with Python-1.7.2 and trying to simply loop through a list and want to add a print statement at the end. But it raises exception as above.
I don't be able to understand why it raise above exception. As for loop reaches it's end and I simply add a print statement outside for loop.
Please! help me to figure out what's going wrong?
After completing the block, you have to press Enter one more time.
When running in interactive interpreter, you need to leave an empty line after a block to indicate the end of the block, otherwise the interpreter assumes that the lines that come after the block are part of the block, and through the invalid syntax error (Like it did in your case).
Example -
>>> for i in li:
... print(i)
... # <---- notice the empty line
>>> print("hi")

Why does `finally: return 42` clear an uncaught exception? [duplicate]

This is some code that is behaving peculiarly. This is a simplified version of the behavior that I've written. This will still demonstrate the weird behavior and I had some specific questions on why this is occurring.
I'm using Python 2.6.6 on Windows 7.
def demo1():
try:
raise RuntimeError,"To Force Issue"
except:
return 1
else:
return 2
finally:
return 3
def demo2():
try:
try:
raise RuntimeError,"To Force Issue"
except:
return 1
else:
return 2
finally:
return 3
except:
print 4
else:
print 5
finally:
print 6
Results:
>>> print demo1()
3
>>> print demo2()
6
3
Why is demo one returning 3 instead of 1?
Why is demo two printing 6 instead of printing 6 w/ 4 or 5?
Because finally statements are guaranteed to be executed (well, presuming no power outage or anything outside of Python's control). This means that before the function can return, it must run the finally block, which returns a different value.
The Python docs state:
When a return, break or continue statement is executed in the try suite of a try…finally statement, the finally clause is also executed ‘on the way out.’
The return value of a function is determined by the last return statement executed. Since the finally clause always executes, a return statement executed in the finally clause will always be the last one executed:
This means that when you try to return, the finally block is called, returning it's value, rather than the one that you would have had.
The execution order is:
try block all completes normally -> finally block -> function ends
try block run and get into exception A -> finally block -> function ends
try block make a return value and call return -> finally block -> popup return value -> function ends
So, any return in the finally block will end the steps in advance.
Note that there has been PEP601 to forbid return statements from finally clauses, but it has been rejected.
It has however been added to the style guide in PEP8 that it should be avoided.

Understanding Exception Handling in Python

I have two questions on exception handling.
Q1) I am slightly unsure as to when exactly the operations within else will be carried out in exception handling. I am unsure when the else block would be executed, which doesn't occur in the code below:
def attempt_float(SecPrice,diffprice):
try:
return float(SecPrice)
except:
return diffprice
else:
print "Did we succeed?"
print attempt_float('7','3')
Q2) When I run the code below:
def attempt_float(SecPrice,diffprice):
try:
return float(SecPrice)
except:
return diffprice
else:
print "Did we succeed?"
finally:
print "Yasdsdsa"
print attempt_float('7','3')
I am unclear as to why the output is:
Yasdsdsa
7.0
When Python encounters a return-statement inside a function, it immediately returns (exits) from the function. This means that when you do:
try:
return float(SecPrice)
...
else:
print "Did we succeed?"
"Did we succeed?" will never be printed because you returned in the try: block, thereby skipping the execution of the else: block.
Your second code piece is different however because you used a finally: block. Code inside a finally: block is always executed, no matter if an exception is raised, you return from a function, etc. This is to ensure that any cleanup code which is important (i.e. frees resources) is always executed and not accidentally skipped.
You can read about this behavior in the docs both here:
When return passes control out of a try statement with a finally
clause, that finally clause is executed before really leaving the
function.
as well as here:
When a return, break or continue statement is executed in the try
suite of a try...finally statement, the finally clause is also
executed "on the way out."
As for why the output is:
Yasdsdsa
7.0
and not:
7.0
Yasdsdsa
the answer is that the print "Yasdsdsa" line is executed in the finally: block before Python is able to print 7.0 (the return value of attempt_float). Put simply, the execution path for Python is:
Return float(SecPrice).
Run the finally: block.
Resume normal execution with the print attempt_float('7','3') line and print 7.0.
In the first case, you return within try, so you never hit the else statement.
In the second one, the finally is executed regardless of how try is exited. From the python docs:
A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. (...) The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break, continue or return statement.
Here is a good example of the order of execution:
>>> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print "division by zero!"
... else:
... print "result is", result
... finally:
... print "executing finally clause"
...
>>> divide(2, 1)
result is 2
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Be sure to read the docs on exceptions!

Python throwing out a random invalid syntax error

Version: Python 3.3.2 (default, Sep 11 2013, 20:16:42)
Hey,
I'm doing some tests with python, fiddling a bit with the shell, but I get a strange error.
>>> a = 5
>>> if a > 0:
... print("a is a positive number.")
... if a < 0:
File "<stdin>", line 3
if a < 0:
^
SyntaxError: invalid syntax
I don't know why this error appears. I know I can use elif or else, but I just want to test.
Help?
This is valid Python syntax when it is located in a module, but in the interactive interpreter you need to separate blocks of code with a blank line.
The handy rule of thumb here is that you can't start a new block with if, def, class, for, while, with, or try unless you have the >>> prompt.
Are you pressing backspace to enter the second if? The shell doesn't like that. It's expecting another line in the logic block, or to be able to execute the block (by pressing enter one more time). The shell can only execute one block at a time, i.e. finish the first if first, then you can enter the second if. You can use elif because it's still considered part of the same logic block.
The REPL is still working on the previous code block. Enter an empty line on its own to terminate it first.
You need a blank line after your print statement, the Python interpreter thinks you're continuing a block until you do that, so you get an indentation error on your second if statement. This is not "invalid", the interactive interpreter is designed to work that way.

Categories