15-110: Principles of Computing - Week 4
"for" Loops and Infinite Loops
"for" loops
- "for" loop over a range
- Range from 0 to y: use range(y+1)
# print the numbers from 0 to 4 (not 5)
for x in range(5):
print x
- Range from x to y: use range(x, y+1)
# print the numbers from 10 to 14 (not 15)
for x in range(10, 15):
print x
- Range from x to y with step z: use range(x, y+1, z)
# print the even numbers from 10 to 14 (not 15)
for x in range(10, 15, 2):
print x
- Range in reverse (use a negative step):
# print the even numbers from 14 to 10 (not 9)
for x in range(14, 9, -2):
print x
- "for" loop over a String
- Without an index
# print each character in a String
for ch in "Wow!":
print ch
- With an index
- the old-fashioned way
# print every other character in a String
s = "Amazing!"
for i in range(len(s)):
if (i % 2 == 0):
print s[i]
- Optional: the newfangled way (with enumerate)
# print every other character in a String
s = "Amazing!"
for i, ch in enumerate(s):
if (i % 2 == 0):
print ch
-
Nested loops
n = int(raw_input("How many rows? "))
for row in range(n):
for col in range(row+1):
print "*",
print
- Infinite while loop with break
while (True):
response = raw_input("Enter a string (or 'done' to quit): ")
if (response == "done"):
break
print " You entered: ", response
print "Bye!"
Readings from the book
Chapter 2 (pp. 36-38) (omit continue and pass statements)
Suggested exercises from the book
Chapter 2: problems 7, 9, 11, 19, 21, 24, 25, 26 (note: random numbers are optional at this point)