Loops

Loops are everywhere

  • Many automated tasks involve loops
  • We need to tell a computer to do something...
    • until a condition it met
    • or for a certain number of times

"Hi, Python, can you do this like...10 times?"

The for loop

So we have this file with lines of stuff

How do we read that in?

We're going to read in a file

We'll look at this more in later weeks, so just roll with not getting the styntax for now

1	Delaware
2	Pennsylvania
3	New Jersey
4	Georgia
5	Connecticut
6	Massachusetts
7	Maryland
8	South Carolina
9	New Hampshire
10	Virginia
11	New York
12	North Carolina
13	Rhode Island
14	Vermont
15	Kentucky
16	Tennessee
17	Ohio
18	Louisiana
19	Indiana
20	Mississippi
21	Illinois
22	Alabama
23	Maine
24	Missouri
25	Arkansas
26	Michigan
27	Florida
28	Texas
29	Iowa
30	Wisconsin
31	California
32	Minnesota
33	Oregon
34	Kansas
35	West Virginia
36	Nevada
37	Nebraska
38	Colorado
39	North Dakota
40	South Dakota
41	Montana
42	Washington
43	Idaho
44	Wyoming
45	Utah
46	Oklahoma
47	New Mexico
48	Arizona
49	Alaska
50	Hawaii

These are tabs

>>> with open('states.txt','rt') as states:
...     states = states.readlines()
... 
>>> print type(states)
<type 'list'>
>>> print states[:2]
['1\tDelaware\n', '2\tPennsylvania\n']
>>> #oo, look at those tabs! if only I could do something...
... 
>>> splitstates = []
>>> for state in states:
...     splitstates.append(state.split())
... 
>>> print splitstates[:2]
[['1', 'Delaware'], ['2', 'Pennsylvania']]
>>> # woohoo!
... 

So that's neat, we have data, now let's do stuff to it

>>> for state in splitstates:
...     num = state[0]
...     name = state[1]
...     print name, "is state", num
... 
Delaware is state 1
Pennsylvania is state 2
New is state 3
Georgia is state 4
Connecticut is state 5
Massachusetts is state 6
.....snip......

A formula for "srsly, just do this like 10 times"

range() is your friend

Combo range() with for to execute something a bunch

Doing stuff until something...

When you don't know how many times it will be

Loops

By Elizabeth W.

Loops

  • 803