Skip to main content

03 | For loop with if and else and method

In class exercise to be demonstrated. As I mentioned in class, this assignment will be expanded

Take this code:

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

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

And change it to this:

items = ['item1', 'item2', 'item3', 'item4']

for item in items:
if item == "item3":
print(item.title()) # you may use any string method you wish.
else:
print(item.upper()) # you man use any string method you wish.

Except you needed to change item variable name to something meaningful and any occurrence of item1 ... item4 to something meaningful to you.

This may seem like a simple exercise if you just copy, paste, and change; but you may find it a bit challenging as any minor error will cause problems.

But try to come up with four things in a list and code it from memory. Where do the commas go? Did you remember the proper position of the quotes? Come back later and try it again. What was the keyword for a loop? Was it a for loop or a while loop? Did you forget the in keyword? How did we get that upper() method in there?

There is actually a lot going on in this little block of code. And you will use this a lot as you continue to code, so practice it over and over so you can do it without referencing the sample. I won't require this for everything, but this it good short bit of code to get into your muscle memory as it covers lists, the for loop and a method, upper(), in one go.