Sv3n
Sv3n

Reputation: 347

Django IndentationError in a working function

I'm so sick of Django. I wrote a Python Function which is working correct. For reasons of visualizations I decided to make a web-page to demonstrate my function.

I added some code to my function:

txt_len = 0          (line 1)
if text:
    txt_len=len(text)

return txt_len  

*it's only a example.
But for a reason I get an IndentationError ,unexpected indent at line 1

Why? can't get it.

Upvotes: 0

Views: 1344

Answers (3)

GreenMatt
GreenMatt

Reputation: 18580

Running the code you present (and removing the "(line 1)" from the first line, which would yield a syntax error) gave "SyntaxError: 'return' outside function". I added a def fn(): statement just above the txt_len = 0 statement. As I expected, that gave an "IndentationError: expected an indented block" . To get this code to work, you need to indent everything in the function, something like:

def fn():
    txt_len = 0
    if text:
        txt_len=len(text)
    return txt_len

If this doesn't fix the problem, please provide more code.

Upvotes: 1

John Percival Hackworth
John Percival Hackworth

Reputation: 11531

Common problems with Python indenting include mixing tabs and spaces. The code example you posted looks okay, but it has been filtered through a formatter already. I'd recommend making sure you use only spaces for indenting.

Upvotes: 0

Let's see the whole function? Line 1 is just for example right? Line 1 would at the very least have to be a function definition for that return line to work.

Did you just paste a function into a django view?

The culprit for mystery indentation errors is almost always mixing spaces and tabs. Do you have invisible characters visible in your editor? Can you run a command to replace tabs with spaces?

Upvotes: 4

Related Questions