Indentation of an IF-ELSE block in Python - python

I am Python newbie and I am working on NLP using Python. I am having an error in writing an if-else block in Python. When I am writing only an if block at that time it is working fine:
if xyzzy.endswith('l'):
print xyzzy
After entering a colon (:) I am pressing Enter and it is automatically taking me to the correct indentation.
But when I am trying to add an else block to it after pressing the Enter key after the print statement, it is considering it to be statement of an IF block only, so it is giving me incorrect indentation as I want an else block after, while when I am trying to write else block my self it is giving me this error.
else:
^
IndentationError: unexpected indent
What should I do after writing print statement? Enter is clearly not working, because it is taking the cursor forward, while when I use space to come to the correct pointer it is giving me an error.

It's hard to see from your post what the problem is, but an if-else is formatted like so
if someCondition:
do_something # could be a single statement, or a series of statements
else:
do_something_else # could be a single statement, or a series of statements
I.e., the else needs to be at the same level as the corresponding if.
See this Python doc/tutorial on if, and this other tutorial too.
Sometimes when your editor does autoindent for you and you edit manually too things might get messed up, so you'll have to figure out how your editor handles indentations (e.g., is it always using tabs or spaces?, what happens if you hit return etc).
Also, be wary of mixing tabs and spaces, that will cause problems too (hard to spot since both are "invisible")
With your updated post:
if xyzzy.endswith('l'):
print xyzzy
else:
something_else

The else should be at the same level of indentation as the if with which it is coupled:
if x:
# Do something
else:
# Do something else
In your case,
if xyzzy.endswith('l'):
print xyzzy
else:
# Something else
Even if your editor is auto-indenting for you, you should still un-indent to make the code syntactically correct.

Getting the indentation correct isn't really a Python issue but rather an issue with the editor that you're using for your source code.
Most editors that understand Python will correctly add one level of indentation after a colon (as you're seeing). Because you can have as many statements as you want in that block of code, the editor has no way to know when to "outdent" the next line for the else.
You have to tell the editor to outdent that line by hitting backspace or Shift + Tab on the line before starting to type.
If you are inserting the else part after the rest of the code is written, make absolutely certain that the characters you use to indent are the same as for the if statement. If the if statement is indented with spaces, use the same number of spaces for else. If the if statement is indented with one or more tabs, use the same number of tabs for the else statement. Don't mix spaces and tabs for indentation.
Don't assume that just because the lines "look" as if they're indented the same that they are indented the same. One may use spaces and one may use tabs (or some combination).

when I use space to come to the correct pointer it is giving me a error
Of course. Using space never makes a "line break", typically this is \n in Unix systems. If you'd open your .py file in a different editor (say Notepad in Windows) you'd see that your else statement is in the same line as print.
Enter is clearly not working because it is taking the cursor forward
Press backspace the correct amount of times to reach the same level of indentation as your IF statement.

I don't agree entirely with the accepted answer. Yes, indention is very important in Python, but to state that the if-else has to always look like that with this formatting is a little bit overboard.
Python allows you a one-liners (even multiple) as long as you don't do anything fancy in there that requires indention in the body of the if, elif or else.
Here are some examples:
choice = 1
# if with one-liner
if choice == 1: print('This is choice 1')
# if-else with one-liners
if choice == 1: print('This is choice 1')
else: print('This is a choice other than 1')
# if-else if with one-liners
if choice == 1: print('This is choice 1')
elif choice == 2: print('This is choice 2')
# if-else if-else with one-liners
if choice == 1: print('This is choice 1')
elif choice == 2: print('This is choice 2')
else: print('This is a choice other than 1 and 2')
# Multiple simple statements on a single line have to be separated by a semicolumn (;) except for the last one on the line
if choice == 1: print('First statement'); print('Second statement'); print('Third statement')
Usually it is not recommended to pack too many statements on a single line because then you lose one of the big features of Python - readability of the code.
Notice also that the above examples can also easily be applied to for and while. You can go even further as to do some crazy nesting of one-liner if blocks if you use the ternary conditional operator.
Here is how the operator usually looks:
flag = True
print('Flag is set to %s' % ('AWESOME' if True else 'BORING'))
Basically, it creates a simple if-else statement. You can embed it with one of your one-liners if you need more branching (but not complex one).
I hope this clarifies the situation a bit and what is allowed and not allowed. ;)

I've been getting this error even when the indentation looked correct.
Viewing in Notepad++ there is an option to see white spaces and Tabs. The error was caused by mixing spaces and tabs to create indentation.
Replacing Tabs with spaces in every line helped to get rid of an error.

Actually, this is a Python IDLE UI issue: Once you hit Enter after the if block finishes, next the else statement is already in intent with the if statement. There isn't any need to provide any tabs or spaces to make indentation. Below is the image for reference.

Related

IndentationError: unindent does not match any outer indentation level even though my indentation is correct [duplicate]

When I compile the Python code below, I get
IndentationError: unindent does not match any outer indentation level
import sys
def Factorial(n): # Return factorial
result = 1
for i in range (1,n):
result = result * i
print "factorial is ",result
return result
Why?
Other posters are probably correct...there might be spaces mixed in with your tabs. Try doing a search & replace to replace all tabs with a few spaces.
Try this:
import sys
def Factorial(n): # return factorial
result = 1
for i in range (1,n):
result = result * i
print "factorial is ",result
return result
print Factorial(10)
IMPORTANT:
Spaces are the preferred method - see PEP 8 Indentation and Tabs or Spaces?. (Thanks to #Siha for this.)
For Sublime Text users:
Set Sublime Text to use tabs for indentation:
View --> Indentation --> Convert Indentation to Tabs
Uncheck the Indent Using Spaces option as well in the same sub-menu above.
This will immediately resolve this issue.
To easily check for problems with tabs/spaces you can actually do this:
python -m tabnanny yourfile.py
or you can just set up your editor correctly of course :-)
Are you sure you are not mixing tabs and spaces in your indentation white space? (That will cause that error.)
Note, it is recommended that you don't use tabs in Python code. See the style guide. You should configure Notepad++ to insert spaces for tabs.
Whenever I've encountered this error, it's because I've somehow mixed up tabs and spaces in my editor.
If you are using Vim, hit escape and then type
gg=G
This auto indents everything and will clear up any spaces you have thrown in.
If you use Python's IDLE editor you can do as it suggests in one of similar error messages:
1) select all, e.g. Ctrl + A
2) Go to Format -> Untabify Region
3) Double check your indenting is still correct, save and rerun your program.
I'm using Python 2.5.4
The line: result = result * i should be indented (it is the body of the for-loop).
Or - you have mixed space and tab characters
For Spyder users goto
Source > Fix Indentation
to fix the issue immediately
Using Visual studio code
If you are using vs code than, it will convert all mix Indentation to either space or tabs using this simple steps below.
press Ctrl + Shift + p
type indent using spaces
Press Enter
On Atom
go to
Packages > Whitespace > Convert Spaces to Tabs
Then check again your file indentation:
python -m tabnanny yourFile.py
or
>python
>>> help("yourFile.py")
If you use notepad++, do a "replace" with extended search mode to find \t and replace with four spaces.
Looks to be an indentation problem. You don't have to match curly brackets in Python but you do have to match indentation levels.
The best way to prevent space/tab problems is to display invisible characters within your text editor. This will give you a quick way to prevent and/or resolve indentation-related errors.
Also, injecting copy-pasted code is a common source for this type of problem.
If you use colab, then you can do avoid the error by this commands.
< Ctrl-A >
< Tab >
< Shift-Tab >
It's all [tab] indentation convert to [space] indentation. Then OK.
Just a addition. I had a similar problem with the both indentations in Notepad++.
Unexcepted indentation
Outer Indentation Level
Go to ----> Search tab ----> tap on replace ----> hit the radio button Extended below ---> Now replace \t with four spaces
Go to ----> Search tab ----> tap on replace ----> hit the radio button Extended below ---> Now replace \n with nothing
I was using Jupyter notebook and tried almost all of the above solutions (adapting to my scenario) to no use. I then went line by line, deleted all spaces for each line and replaced with tab. That solved the issue.
For what its worth, my docstring was indented too much and this also throws the same error
class junk:
"""docstring is indented too much"""
def fun(): return
IndentationError: unindent does not match any outer indentation level
I'm using Sublime text in Ubuntu OS. To fix this issue go to
view -> Indentation -> convert indentation to tabs
It could be because the function above it is not indented the same way.
i.e.
class a:
def blah:
print("Hello world")
def blah1:
print("Hello world")
Since I realize there's no answer specific to spyder,I'll add one:
Basically, carefully look at your if statement and make sure all if, elif and else have the same spacing that is they're in the same line at the start like so:
def your_choice(answer):
if answer>5:
print("You're overaged")
elif answer<=5 and answer>1:
print("Welcome to the toddler's club!")
else:
print("No worries mate!")
I am using Sublime Text 3 with a Flask project. I fixed the error using View > Indentation > Tab Width: 4 after unselected Indent Using Spaces
This is because there is a mix-up of both tabs and spaces.
You can either remove all the spaces and replace them with tabs.
Or,
Try writing this:
#!/usr/bin/python -tt
at the beginning of the code. This line resolves any differences between tabs and spaces.
I had the same issue yesterday, it was indentation error, was using sublime text editor. took my hours trying to fix it and at the end I ended up copying the code into VI text editor and it just worked fine. ps python is too whitespace sensitive, make sure not to mix space and tab.
for Atom Users, Packages ->whitspace -> remove trailing whitespaces
this worked for me
I had a function defined, but it did not had any content apart from its function comments...
def foo(bar):
# Some awesome temporary comment.
# But there is actually nothing in the function!
# D'Oh!
It yelled :
File "foobar.py", line 69
^
IndentationError: expected an indented block
(note that the line the ^ mark points to is empty)
--
Multiple solutions:
1: Just comment out the function
2: Add function comment
def foo(bar):
'' Some awesome comment. This comment could be just one space.''
3: Add line that does nothing
def foo(bar):
0
In any case, make sure to make it obvious why it is an empty function - for yourself, or for your peers that will use your code
Firstly, just to remind you there is a logical error you better keep result=1 or else your output will be result=0 even after the loop runs.
Secondly you can write it like this:
import sys
def Factorial(n): # Return factorial
result = 0
for i in range (1,n):
result = result * i
print "factorial is ",result
return result
Leaving a line will tell the python shell that the FOR statements have ended. If you have experience using the python shell then you can understand why we have to leave a line.
For example:
1. def convert_distance(miles):
2. km = miles * 1.6
3. return km
In this code same situation occurred for me. Just delete the previous indent spaces of
line 2 and 3, and then either use tab or space. Never use both. Give proper indentation while writing code in python.
For Spyder goto Source > Fix Indentation. Same goes to VC Code and sublime text or any other editor. Fix the indentation.
I got this error even though I didn't have any tabs in my code, and the reason was there was a superfluous closing parenthesis somewhere in my code. I should have figured this out earlier because it was messing up spaces before and after some equal signs... If you find anything off even after running Reformat code in your IDE (or manually running autopep8), make sure all your parentheses match, starting backwards from the weird spaces before/after the first equals sign.
I had the same error because of another thing, it was not about tabs vs. spaces. I had the first if slightly more indented than an else: much further down. If it is just about a space or two, you might oversee it after a long code block. Same thing with docstrings:
"""comment comment
comment
"""
They also need to be aligned, see the other answer on the same page here.
Reproducible with a few lines:
if a==1:
print('test')
else:
print('test2')
Throws:
File "<ipython-input-127-52bbac35ad7d>", line 3
else:
^
IndentationError: unindent does not match any outer indentation level
I actually get this in pylint from a bracket in the wrong place.
I'm adding this answer because I sent a lot of time looking for tabs.
In this case, it has nothing to do with tabs or spaces.
def some_instance_function(self):
json_response = self.some_other_function()
def compare_result(json_str, variable):
"""
Sub function for comparison
"""
json_value = self.json_response.get(json_str, f"{json_str} not found")
if str(json_value) != str(variable):
logging.error("Error message: %s, %s",
json_value,
variable) # <-- Putting the bracket here causes the error below
#) <-- Moving the bracket here fixes the issue
return False
return True
logging.debug("Response: %s", self.json_response)
# ^----The pylint error reports here

Reverse Tab in Python IDLE (3.7)

Is there a keyboard shortcut for reverse-tab in the Python IDLE?
I am trying to write an if-elif-else statement but cannot reverse-tab to properly indent the elif statement. I've tried shift+tab and shift+ctrl+tab.
For example, I can write this...
if x < 0:
print('Less than Zero')
but when I try to add the elif statement...
elif x == 0:
print('Zero')
I get the following error message:
SyntaxError: unindent does not match any outer indentation level
ctrl+[ de-indents highlighted code. ctrl+] indents.
You can see all the shortcuts if you look in the "Edit" menu at the top of the editor.
For reverse
ctrl+[
For Opposite
ctrl+]
Use the back space key to dedent. It is easiest if one does so before entering any code. If there is already code on the line, put the edit cursor between the end of the indent and the beginning of the code before hitting backspace. Note that in IDLE, one enters and edits, and submits complete statements for execution. Hence no secondary prompts. Example:
>>> a, x, y = 1, 2, 3 # Bind some names. This is one statement.
>>> if a: # When you hit return, IDLE see that you entered the header
# of a compound statement and indents the next line with a Tab.
# Note that I have to use 8 spaces here instead of a tab.
print(x) # When you hit return, IDLE keeps the same indent.
# Use Backspace [<--] to dedent back to the margin.
else: # Do not line up 'else' with 'if' by adding 4 spaces.
# Since this is another header, an indent is added on the next line.
print(y) # No header, indent kept the same.
# Hit Return to enter blank line
The final blank line signals that the compound statement is complete and should be executed. Until then, one can edit any part of the statement.
I am a bit stunned that 3 people would suggest the awkward and much harder workaround of selecting the line or at least the indent and using control-[. I am thinking about how to make the easy way more obvious.
I am aware that having 'if', 'elif', and 'else' not lined up is a nuisance. I intend to fix this.
What your doing is the shortcut on Spyder, but no, in idle, you have to do:
Ctrl+[
And the opposite would be:
Ctrl+]

Commented blocks/indents interfering with code

The problem is best explained by just showing the code:
a = True
b = True
while True:
"""
A
"""
if a == True:
pass
"""
B
"""
elif b == True:
pass
The issue being that there is a syntax error at "elif b", though when removing the comments, the issue disappears. I tried removing the indents on the comments which resulted in an expected indent on the closing comment line after "A". I know I could switch to using "#" to comment sections, though """ makes things much clearer and is more convenient for large chunks. Perhaps I'm missing something obvious, I would appreciate any help.
String literals aren't comments. You can sometimes sort of pretend they're comments, but they're not, and the fact that they're not is finally biting you.
An elif has to appear immediately after the end of the block associated with the preceding if or elif. There can be comments and whitespace in between, but no statements, and strings count. Use real comments, with #.
If you really want to keep pretending strings are comments, you can indent the B string into the body of the if, but it won't line up cleanly with the block it's intended to be a comment on, and you'll just keep having to mess with your formatting to patch up the differences between comments and string literals.
You're creating a new string when you use """triple quotes""". So, you essentially have an un-indented block of code before your elif, which requires a preceding if statement. The improper tabbing on the quotes ends your if block. Once your parser reaches the elif block, it doesn't have a matching if block, hence the error.
Triplequotes are used as docstrings in places, and can act like comments, but they're not actually comments.
Reference (search for """)

Auto correct indentation errors in Python

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

Why do I get "expected an indented block" when I try to run my Python script? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I have an error which says "expected an indented block"
Could you please guide me on how to deal with this error. Thank you:)
Code example:
for ch in f: ( translatedToken = english_hindi_dict[ch] ) if (ch in english_hindi_dict) else (translatedToken = ch)
Editing answer to match the code example.
for ch in f: ( translatedToken = english_hindi_dict[ch] ) if (ch in english_hindi_dict) else (translatedToken = ch)
is just not valid Python.
First, readability count. Your code is hard to read and so, is hard to debug. What's "ch" and "f" ? What's more, you can do one liner in Python but it's not recommended, so put the for in a separate line. Then indent.
for chunk in file:
( translatedToken = english_hindi_dict[chunk] ) if (chunk in english_hindi_dict) else (translatedToken = chunk)
Now we can see what's wrong. You make variable assignments in a conditional statement. This is not allowed in Python. I'm guessing you have a C/C++ background and are used to do that. In Python you can't, to prevent you from writing obfuscated code. So you end up with:
for chunk in file:
translatedToken = english_hindi_dict[chunk] if chunk in english_hindi_dict else chunk
This piece of code should work, provided you use Python 2.5+. But the ternary operator is not available in older Python version yet. Let's make it a bit friendlier:
for chunk in file:
translatedToken = chunk
if chunk in english_hindi_dict:
translatedToken = english_hindi_dict[chunk]
You may argue that it's longer to write, and you'd be right. But you spend more time reading code than writing it, so it make sense to make it easy to read. Or course, once you have the Python grip, you will try to make it work in a more pythonic way. Ever heard of EAFTP?
for chunk in file:
try:
translatedToken = english_hindi_dict[chunk]
except KeyError:
translatedToken = chunk
But Python is full of surprises, and you'll learn that most of these classic use cases have been already taken care of. The standard library often provides an elegant and short yet readable solution:
for chunk in file:
translatedToken = english_hindi_dict.get(chunk, chunk)
As a conclusion: don't try to write Python as you wrote C, or Java as you would write Perl. Other tool, other style.
To fix this problem, fire your editor "search and replace" feature and make a huge "replace all" to change all the tabs by 4 spaces, or the contrary. Then indent all your blocks, and finally align all the instructions in the same block.
Funny that didn't appear before on SO. After all, it's true it's not that obvious.
In Python, you separate blocks using spaces or tabs, not "{".
So any time you go down a block (a function, a loop, a class, etc), you have to indent your code. This is not just good practice, this is mandatory. Your program will crash if you don't.
Now, most of the time, you get this error because you did indent, but used tabs and spaces. In a Python program, you should use either tabs or spaces, but never both in the same files.
E.G:
if (age > 18)
{
printf("You can vote")
}
Becomes:
if age > 18:
print("You can vote")
In most languages, you could do:
if (age > 18)
{
printf("You can vote")
}
In Python you can't:
if age > 18:
print("You can vote")
raises an exception. What's more, you must align all the instruction of the same block, so:
if age > 18:
print("You can vote")
print("How cool is that ?")
Is fine, but:
if age > 18:
print("You can vote")
print("How cool is that ?")
raises an exception.
Eventually, you can't mix tab and spaces in the same block. So:
if age > 18:
print("You can vote")
print("How cool is that ?")
looks good, but will raises an exception. To avoid this problem, just stick to tabs or spaces. The PEP8, the text one most use as a reference for coding style recommend using 4 spaces.
Most editors have a global "search and replace" feature that let you fix any problem you can have with that. Some like Geany or Ulipad even have a "replace all tabs with spaces" feature.
You are probably mixing tabs with spaces. It looks indented but it really isn't.
Your code gives me a different error:
for ch in f: \
( translatedToken = english_hindi_dict[ch] ) \
if (ch in english_hindi_dict) else (translatedToken = ch)
↑
SyntaxError: invalid syntax
Maybe you meant:
for ch in f:
if ch in english_hindi_dict:
translatedToken = english_hindi_dict[ch]
else:
translatedToken = ch
Maybe you meant instead:
for ch in f:
translatedToken = english_hindi_dict[ch] if ch in english_hindi_dict else ch
Both should run just fine, and I expect the second to be faster than the former
They both can be optimized into translated = str(english_hindi_dict.get(ch, ch) for ch in f) but that's not the point of the question.
Python is a language that relies heavily on indentation to decide program structure unlike C and some other languages that use braces for this purpose.
When you have a statement like:
if true:
pass
it will complain because there's no indented statement for the if. You would need to fix it to be:
if true:
pass
That sounds like the sort of error you have, though it may have been more obvious had you posted the actual code. When stating a problem, it's a good idea to give the code and explain what the expected behaviour was and how that related to the actual behaviour. You'll make the lives of those trying to help you out that much easier :-)
Also keep in mind that you may get this problem even if your code looks right. Mixing spaces and tabs in your source code can often lead to this.
IndentationErrors can be caused by a lot if different things. Off the top of my head:
Forgetting to indent at all.
Python uses indents to delimit syntactic blocks. For example:
if will_is_awesome:
print "You're right"
else:
print "You lie!"
You will get an IndentationError: expected an indented block error if you forget to indent. For example:
if will_is_awesome:
print "You're right"
else:
print "You lie!"
Commenting out an indented block.
For example:
if light_is_green:
go_now()
else:
# go_anyway()
do_something_else()
This will produce an IndentationError: expected an indented block because the comment makes the line after else: look empty to the parser. Adding a pass statement will fix the problem. Eg:
if light_is_green:
go_now()
else:
# go_anyway()
pass
do_something_else()
Mixed tabs and spaces in indents.
Tab stops can vary between different machines and editors. If you mix tabs and spaces just right, you can get your error, but it usually produces IndentationError: unindent does not match any outer indentation level, so it's unlikely to be your problem. It's worth knowing anyway. It is advisable to never use tabs in Python code.
Python uses indentation (spaces/tabs in front of your code lines) to indicate where a block of code starts and ends, relative to what python statement precedes it.
So, taking PHP for example:
if ($blah == 'foo')
{
// this is line 1 of my code block
// this is line 2
}
Would, under python, be:
if blah == 'foo':
# this is line 1 of my code block
# this is line 2
pass
Could you please provide some code, together with the exact error?
Python determines blocks by indentation, not by characters { and } like C/C++/Java/PHP/... does or by if/endif or begin/end pairs found in some other languages. So you have to be careful about indentation - also mixing tabs and spaces is not good.

Categories

Resources