Files
python-2020-5-day-class/docs/day3.md
2020-11-17 19:26:20 -05:00

2.0 KiB

Day 3

"For"

Let's cover our first loop - the "for" loop. In Python the "for" loop is absurdly powerful. Let me show you why.

Looping without code

"For" loops in Python make intuitive sense even without code. I can demonstrate with this basket of fruit:

|         |
|  apple  |
|  banana |
 \ pear  /
  \_____/

For each fruit I want you to take it out of the basket say its name. You start with the apple, since it's at the top, and say "apple". Then you'd take out the banana and say "banana". Finally you'd take our the pear and say "pear".

In Python our "basket" is a list. Lists look like this:

["apple", "banana", "pear"]

They're very similar to tuples. A list is "ordered", the first item in the list will always be the apple - much like the top item in the basket will always be the apple.

If I asked you to repeat the basket exercise above but with our python list - remove each item and say its name - you'd start with the apple, then remove the banana, and finally remove the pear.

Looping with code

You saying the names of fruit out loud is funny but not very practical. Instead I want you to print the names of the fruit from our basket in the Python interpretor.

  1. Start you interpretor by typing python and pressing ++enter++

  2. In your interpretor type the following:

    fruits = ["apple", "banana", "pear"]
    for fruit in fruits:
        print(fruit)
    

    You should see the fruit print out:

    >>> fruits = ["apple", "banana", "pear"]
    >>> for fruit in fruits:
    ...     print(fruit)
    ...
    apple
    banana
    pear
    >>>
    

    you've just used a for loop!

  3. So we can do something with each item in a list. But what if we need the index of each item? Type the following:

    fruits = ["apple", "banana", "pear"]
    for index, fruit in enumerate(fruits):
        print(f"fruit {fruit} is at index {index}")
    

    with enumerate we can capture the position of the item and the item itself in the list.