Lesson 6: For Loops and Arrays

A for loop counts from a start number to an end number. An array holds a list of related values.


In [10]:
# For loop example 
for counter in range(3, 7):
    print counter
    print "Whee!"
print "Done."


3
Whee!
4
Whee!
5
Whee!
6
Whee!
Done.

In [9]:
# Arrays example
children = ["Sally", "Bobby", "Tommy", "Tonya"]
ages = [12, 9, 7, 5]

print "Sally's age is ", ages[0]
print "Bobby's age is ", ages[1]
print "Tommy's age is ", ages[2]
print "Tonya's age is ", ages[3]

for count in range(0, 4):
    print "Child ", children[count], " is ", ages[count], " years old."


Sally's age is  12
Bobby's age is  9
Tommy's age is  7
Tonya's age is  5
Child  Sally  is  12  years old.
Child  Bobby  is  9  years old.
Child  Tommy  is  7  years old.
Child  Tonya  is  5  years old.

How would you write a for loop to walk through this list of day numbers and temperatures, and print the temp for each day?


In [12]:
# July temperatures
day   = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
temp  = [81, 82, 80, 75, 74, 80, 78, 75, 72, 74, 76]

# print something like:
# July 10: High of 81
# July 11: High of 82
# ...

Hot Days

Write code that walks through this list of values, prints just the number for temps of 90 and below, but prints the number with "Hot!!!" after it for any temperature above 90.


In [13]:
temp  = [81, 82, 80, 95, 84, 89, 90, 95, 82, 84, 96]

Day Camp: Present/Absent

Alex runs a day camp for children. He wants a small program to keep track of what children are present or absent each day. The program should let the user type in a child's name, and then A or P for absent or present. It should keep track of the whole list of children this way (in an array for the names, and another array for A or P). There are exactly 6 children coming to camp this time, so the program will stop after exactly 6 names. Once the names are all entered, the program should print "Present:" and a list of the names of children who are present that day. Then it should print "Absent:" and a list of the names of children who are absent that day.


In [ ]:

Challenge: Groceries

Zalia wants a grocery calculator. Write a program that asks the user to enter the name of a grocery item, the price of the item, and then the quantity of that item. It should store each of those in arrays. Then it asks for the next item. It keeps asking for more items like this until the user puts in "quit" as the item name.

Then, it goes through the arrays once more. It calculates the price * quantity for each item, and adds up a total cost for the entire order. Then it prints out the total cost.

This challenge will use arrays, for loops, and a while loop. You may have an easier time planning this on paper first.


In [ ]:
# Here are some variable name ideas to get you started. 
# You can change these lines as necessary.

total = 0.00
items = [ "", "", "" ]
prices = [ ]
quantities = [ ]

In [ ]:


In [ ]:


In [ ]:


In [ ]: