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

2024/11/15 21:28:06

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

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 = chunkif 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.

https://en.xdnf.cn/q/71420.html

Related Q&A

python run command as normal user in a root script

I have a python script that is launched as root, I cant change it. I would like to know if its possible to exectute certain lines of this script (or all the script) as normal user (I dont need to be ro…

Compare values of two arrays in python

How can i check if item in b is in a and the found match item in a should not be use in the next matching? Currently this code will match both 2 in b.a = [3,2,5,4] b = [2,4,2]for i in b:if i in a:prin…

How to count the number of digits in numbers in different bases?

Im working with numbers in different bases (base-10, base-8, base-16, etc). Im trying to count the number of characters in each number. ExampleNumber: ABCDEF Number of digits: 6I know about the method …

Pandas KeyError using pivot

Im new to Python and I would like to use Python to replicate a common excel task. If such a question has already been answered, please let me know. Ive been unable to find it. I have the following p…

Not found: Container localhost does not exist when I load model with tensorflow and flask

I am a newbie research Deeplearning. I load a saved model with tensorflow and made a API with flask but I get error Container localhost does not exist. when I predict, please help me fix it. Thank you.…

Python: simplifying nested FOR loop?

I am wondering if there is a way to simplify the nested loop below. The difficulty is that the iterator for each loop depends on things from the previous loops. Here is the code:# Find the number of co…

NLTK Data installation issues

I am trying to install NLTK Data on Mac OSX 10.9 . The download directory to be set, as mentioned in NLTK 3.0 documentation, is /usr/share/nltk_data for central installation. But for this path, I get …

Why does the simplest requests_mock example fail with pytest?

I have a peculiar problem with requests_mock. I want to use it with pytest to test my API wrapper library.Ive tried to use the first example in the requests_mock docs, except I put it in a test_mock()-…

Error installing PyCurl

I tried installing pycurl via pip. it didnt work and instead it gives me this error.running installrunning buildrunning build_pyrunning build_extbuilding pycurl extensiongcc-4.2 -fno-strict-aliasing -f…

Serializing objects containing django querysets

Django provides tools to serialize querysets (django.core.serializers), but what about serializing querysets living inside other objects (like dictionaries)?I want to serialize the following dictionar…