Anshuman singh
Anshuman singh

Reputation: 41

If else error "IndentationError: unexpected indent"

I'm trying to learn Python and I'm running the code:

for car in cars:
  if car == 'bmw':
      print(car.upper())
  else:
      print(car.title())

But I'm getting this error:

for car in cars:
...    if car == 'bmw':
...       print(car.upper())
...           else:
  File "<stdin>", line 4
    else:
    ^
IndentationError: unexpected indent

How can I improve the code?

Upvotes: 1

Views: 8195

Answers (2)

baduker
baduker

Reputation: 20042

This should help I hope.

cars = ['audi', 'bmw']
for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())

Also, do not mix tabs and spaces when indenting your code. This could be the reason why you're getting the error.

Upvotes: 1

Trelzevir
Trelzevir

Reputation: 765

As the error suggests, the problem is with the indentation of the else statement. It should be at the same indentation level as the if statement in the for loop.

if...:
    .....
else:
    .....

Upvotes: -1

Related Questions