Go to: Na-Rae Han's home page  

Python 3 Notes

        [ HOME | LING 1330/2330 ]

Tutorial 14: for Loops

<< Previous Tutorial           Next Tutorial >>
On this page: using a for loop.

Video Tutorial


Python 3 Changes

print(x,y) instead of print x, y

Video Summary

  • Loops are a way to repeat a set of actions a specific number of times under certain conditions. The "for" loop is a popular type of loop. We first define a sequence to loop over: a list called "theMotto" which is defined as ['you', 'only' 'live' 'once' '(YOLO)'].
  • The for loop has multiple parts. The first line looks like for x in y:, where y represents the sequence to loop over and x each item in it. For example, the tutorial uses for item in theMotto: as the first part of the loop, where "item" is automatically defined as anything contained within your list, and "theMotto" is the list in question.
  • Notice the colon ":" at the end of the line; this tells Python that there is more information to follow within your command. As such, after typing for item in theMotto: and pressing the Enter Key, Python will automatically indent the cursor on the next line. From there, you can enter the actual action that you want Python to execute. The tutorial uses the simple function print(item):
     
    >>> for item in theMotto:
            print(item)	
    
    When completed, this simple loop will print each of the items within the list theMotto with a line break between each of them.
  • You can also have a single loop execute multiple commands. For example, repeating the same loop as before, but adding a print(len(item)) statement in addition, will return each of the items in the theMotto as well as their respective lengths in characters.
  • It does not matter which variable name you use following "for..." in your loop. Names like "item" and "thing" are used as generic placeholders, which Python knows to interpret as "any item"

Learn More

  • The for ... in loop is adaptive: you can use it with other sequence types including a string. When used on a string, the iteration is done on every character:
     
    >>> for i in 'hello': 
            print(i)  
    	  
    h
    e
    l
    l
    o 
    
  • for loops are simple yet a powerful and versatile tool. See More on for Loops to learn all about them.

Explore

  • Anne Dawson has many excellent examples: search for "iteration" on the page. Searching "for loop" will get you many examples of for used in conjunction with the range() function.