Why do I get "expected an indented block" when I try to run my Python script? [closed]
开发者_如何学C
Closed 4 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.
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.
IndentationError
s 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 afterelse:
look empty to the parser. Adding apass
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.
精彩评论