# loops.py
# Walker M. White (wmw2)
# September 30, 2012
"""Simple module showing off for loops"""
import string
def simple_for(seq):
"""Prints out each element of the list seq
Precondition: seq a sequence (string or list)"""
for x in seq:
print 'Current element is '+`x`
def count_for(seq):
"""Prints out each element of the list seq (with counter)
Precondition: seq a sequence (string or list)"""
counter = 0 # tracks the current element of the list
for x in seq:
print 'The element in position '+`counter`+' is '+`x`
counter = counter + 1 # increment the counter
def num_digits(s):
"""Returns: number of chars in s that are digits
Precondition: s a string"""
total = 0 # Holds the digit count
for c in s:
if c in string.digits:
total = total + 1 # Increment if character is a digit
return total
def no_blanks(s):
"""Returns: copy of s with no blanks
Precondition: s a string"""
result = '' # Holds the copy string
for c in s:
if not c in string.whitespace:
result = result+c # glue it to the result
return result
def isprime(n):
"""Returns: True if no integer in 2..n-1 divides n, else False
Precondition: n > 1 an int"""
result = True
for x in range(2,n):
if n % x == 0: # x "goes evenly" into n
result = False
return result
def sum_of_odd_squares(m, n):
"""Returns: sum of squares of odd integers in the range m..n.
Precondition: n >= m are ints"""
total = 0
for x in range(m,n):
if x % 2 == 1: # odd
total = total + (x*x)
return total