Create Your Own - Indentation Question


#1

https://www.codecademy.com/en/courses/python-beginner-en-cxMGf/2/6?curriculum_id=4f89dab3d788890003000096

My code below is intended to be a list of lens brands that a store is selling, and it asks the user what kind of camera they own. Next, the for loop iterates through the list of lens brands, and checks to see if any of the brands inside match the brand of the user's camera.

With the code written as:

lens_brands = ['Canon', 'Nikon', 'Olympus', 'Fuji', 'Sony']
your_camera = raw_input('Which brand of camera do you own?')
for brand in lens_brands:
    if brand == your_camera:
        print("We have a lens that is compatible with your camera!")
        break
    else:
        print("We may not have a lens that is compatible with your camera.")

The problem is that if I type Fuji, the output will appear as:

Which brand of camera do you own? Fuji
We may not have a lens that is compatible with your camera.
We may not have a lens that is compatible with your camera.
We may not have a lens that is compatible with your camera.
We have a lens that is compatible with your camera!
None

I only want it to print one statement, which is that they do have a lens compatible with the user's camera.

When I remove the indentation for the else statement, it works as intended when I type something such as Fuji.

lens_brands = ['Canon', 'Nikon', 'Olympus', 'Fuji', 'Sony']
your_camera = raw_input('Which brand of camera do you own?')
for brand in lens_brands:
    if brand == your_camera:
        print("We have a lens that is compatible with your camera!")
        break
else:
    print("We may not have a lens that is compatible with your camera.")

I may know the answer as to why, but can someone verify this? I think the reason the second one works is because the for loop iterates through lens_brands to see if the brand matches the user's camera brand. However, it doesn't do anything else, and only checks if they match. If they don't match, it checks the next one, and the next one, and so on. Once it finds that none of them match, it moves on to the else statement, simply because the else statement is outside of that for loop.


#2

else is not a statement on its own, if-, while-, and for- statements have optional else's, the latter two having to do with whether the loop encountered a break or not


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.