Reputation: 4171
Let me explain the problem with some demo codes:
def my_func:
if not a:
#operations A here.
try:
#operations B here.
except:
#operations C here.
The problem here is that the try-except clause seems to be included into the if statement. Only if "not a" is True, the try-except clause statements would be executed, other wise they would never be executed.
I tried to shrink some indent space before try-except clause as follow:
def my_func:
if not a:
#operations A here.
try:
#operations B here.
except:
#operations C here.
Now everything seems to work as try-except is executed independently with the if statement.
Any explanation is really appreciated.
Upvotes: 0
Views: 250
Reputation: 101959
You have mixed tabs with spaces in your indentation, this lead the interpreter to misinterpret the indentation levels, thinking that the try
was one level higher:
>>> if True:
... if True: # indentation with 4 spaces. Any number will do
... a = 1 # indentation with a tab. Equals two indents with spaces
... else: # indentation with 4 spaces
... a = 2
...
>>> a # as if the "a = 1" was inside the second if
1
To check whether this is the problem launch the program via python -tt
which raises an error if it finds mixed tabs and spaces. Also note that when using python3 it automatically runs with the -tt
option, not allowing mixing tabs and spaces.
Upvotes: 1