# loops.py
# Walker M. White (wmw2)
# October 6, 2013
"""Simple module showing off for simple 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 '+str(x)
print 'Done with function'
def sum(thelist):
"""Returns: the sum of all elements in thelist
Precondition: thelist is a list of all numbers
(either floats or ints)"""
result = 0
for x in thelist:
result = result+x
print 'Adding '+str(x)+' yield '+str(result)
return result
def num_ints(thelist):
"""Returns: the number of ints in thelist
Precondition: thelist is a list of any mix of types"""
result = 0
for x in thelist:
if type(x) == int:
print str(x)+' is an int'
result = result+1
return result
def copy_add_one(thelist):
"""Returns: copy with 1 added to every element
Precondition: thelist is a list of all numbers
(either floats or ints)"""
mycopy = [] # accumulator
for x in thelist:
x = x+1
mycopy.append(x) # add to end of accumulator
return mycopy
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