user974703
user974703

Reputation: 1653

Python if syntax 3.2.2

This is a really basic question, but what is wrong with this code?

for row in rows:
    if row["Type"] = 'DEADLINE':
        print (row["Title"])

I get the error TabError: inconsistent use of tabs and spaces in indentation pointing to the colon at the end of the if.

Sorry if this is too newbie for SO, but I cant determine if its an issue with going from 2.x python to 3.x or if it's just syntax I have yet to learn.

Thanks

EDIT: Problem solved. I didn't realize my text editor had it's 'turn tabs into spaces' feature turned off. So yes, it was a mix of tabs and spaces. I assumed the message meant I had an inconsistant use of whitespace in general, like there were too many spaces or something.

And yes, i realize the single = is a syntactic error, it was something I was trying to remove the TabError, but is obviously wrong.

Upvotes: 1

Views: 1958

Answers (3)

Mark Byers
Mark Byers

Reputation: 839114

The problem appears to be the whitespace you use to indent your code. You have a mixture of tab characters and spaces. I suggest you use you "show whitespace" in your editor and change all the tabs in your code to the correct number of spaces.

If your editor doesn't have a "show whitespace" feature, you can spot the tab characters by temporarily inserting a space at the beginning of the line and watching to see if the end of the line also moves by exactly one space. If it either doesn't move or it jumps by (for example) 4 or 8 characters then you have a tab character somewhere on that line.

Upvotes: 2

Thomas
Thomas

Reputation: 182063

You are probably mixing tabs and spaces for your indentation, just like the error message says.

Some editors have the annoying habit of replacing 8 spaces by a tab automatically, so your code might actually look like this:

for row in rows:
    if row["Type"] = 'DEADLINE':
->print (row["Title"])

where -> represents a tab character.

Tell your editor to make tabs visible, and not to replace spaces again.

Alternatively, consistently indent using one tab per indent level.

Upvotes: 7

Eli Bendersky
Eli Bendersky

Reputation: 273796

What's really wrong is your using single = instead of double == in the condition inside the if statement.

Apart from that, make sure you configure your editor to only use spaces and never tabs when editing Python code.

Upvotes: 3

Related Questions