Why doesn’t print return all the items in a list?

Asked

Viewed 57 times

-2

The following code should return all cars from the following list:

cars = ['audi','bmw','subaru','toyota']

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

But he only returned: BMW Toyota

What’s wrong with it?

  • I couldn’t reproduce the problem: https://ideone.com/8RqW2K

  • That’s weird. I’m using IDLE. I’m going to test on Atom. Thank you.

1 answer

1


Your formatted code is as follows:

cars = ['audi','bmw','subaru','toyota']

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

The problem is that the else is at the wrong indentation level. It is in your code referring to the is. You want it to be at the same indentation level as the if:

cars = ['audi','bmw','subaru','toyota']

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

# Audi
# BMW
# Subaru
# Toyota

Browser other questions tagged

You are not signed in. Login or sign up in order to post.