1

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?

3
  • 1
    Welcome to StackOverflow. Please use backticks to format your code. Commented Mar 5, 2018 at 21:38
  • 2
    Does this answer your question? I'm getting an IndentationError (or a TabError). How do I fix it? Commented Dec 20, 2023 at 5:34
  • The error message does not seem to match the code. The error message suggests the "else" has actually been indented seven more spaces than the "if", thus causing "IndentationError: unexpected indent". The indentation levels are not required to be consistent. Commented Jan 14, 2024 at 2:04

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

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:
    .....

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.