Abhishek Guddu
Abhishek Guddu

Reputation: 25

indent error in python while using if statements inside for loop

I used the following code:

for item in users_dict['items']:
    sl_no = sl_no + 1
    user_id_pass = item['user_id']
    account_id_pass = item['account_id']
    Name_pass = item['display_name']

    if 'age' in item:
        age_pass = item['age']
    else:
        age_pass = 0

    stack_link_pass = item['link']
    user_type_pass = item['user_type']
    Location_pass = item['location']

    if 'website_url' in item:
        website_link_pass = item['website_url']
    else:
        website_link_pass = 'NA'

I am getting this error:

 user_id_pass = item['user_id']
    ^
IndentationError: unexpected indent

please help me out

Upvotes: 2

Views: 4079

Answers (3)

Vinay Verma
Vinay Verma

Reputation: 1098

To Enhance it more for someone who gets into this situation. In your most widely used code editors. VSCode or Sublime Text.

Type a sequence "Ctrl+Shift+P" a command box will open

In that type "Indentation: Convert to Spaces" or similarly "Indentation: Convert to Tabs". It will manage all the tabs and spaces and convert them to a uniform type. Correct the formatting and you are good to go.

enter image description here

Upvotes: 0

JasonG
JasonG

Reputation: 137

In Python, you can only use one or the other, tabs or spaces, to indent your code. Since tabs and spaces are encoded differently, the interpreter can't tell where your if statement ends. Backspace over all of your indentations, then just tab or space every line the number of indents you prefer.

Upvotes: 0

fnocetti
fnocetti

Reputation: 243

As I see that all your lines are indented with the correct amount of spaces, please check that your using either tabs or spaces to indent.

For example you may have run into this situation:

    {4 spaces}sl_no = sl_no + 1
    {--1 tab-}user_id_pass = item['user_id']
    {4 spaces}account_id_pass = item['account_id']

Upvotes: 2

Related Questions