Python: for Loops

Go to Chapter 21 of A Smarter Way.

Remember an earlier for loop we used:

friends = ['bill', 'jeff', 'jim']

for friend in friends:
    print("Hello, " + friend.title() + "!")

Often we use these inside if-tests:

friends = ['bill', 'joel', 'jeff', 'jim', 'scott', 'todd']
people_at_party = ['joel', 'jim']

# Go through all the people who are present, 
# and greet our friends.
for person in people_at_party:
    if person in friends:
        print("Hello, %s!" % person.title())

Exercises

See http://www.asmarterwaytolearn.com/python/21.html

See http://introtopython.org/if_statements.html

  1. In your examples.py script, try each of the code blocks above.
  2. Do any of them need to be debugged? Do it if necessary.

 

One Reply to “Python: for Loops”

Comments are closed.