CSC111 Lab 3 2011 Solutions
--D. Thiebaut 12:31, 22 September 2011 (EDT)
# Lab3 solution programs
# D. Thiebaut
# single for-loops
def main1():
for i in range( 3, 8 ):
print( i )
print( '\n', '-' * 80 ,'\n' )
# without range()
for i in [3, 4, 5, 6, 7]:
print( i )
print( '\n', '-' * 80 ,'\n' )
# only even numbers between 4 and 20 included
for i in range( 4, 21, 2 ):
print( i )
print( '\n', '-' * 80 ,'\n' )
# only odd nuumbers between -3 and 19 included
for i in range( -3, 20, 2 ):
print( i )
print( '\n', '-' * 80 ,'\n' )
# user-controlled loop
print( "I will print a list of numbers for you." )
start = eval( input( "Where should I start? " ) )
stop = eval( input( "What is the last number in the series? " ) )
for i in range( start, stop+1, 1 ):
print( i )
def main2():
print( '\n', '-' * 80 ,'\n' )
# real challenge
for i in range( 0, 10 ):
noStars = i
noDots = i*2
noDashes = 4+i
noQMarks = noDots
#print( noStars, noDots, noDashes, noQMarks )
print( noStars *'*' + noDots * '.' + noDashes *'-' + noQMarks *'?' )
def main3():
print( '\n', '-' * 80 ,'\n' )
farm = [ "dog", "cat", "horse" ]
farm.append( "pig" )
# print the contents of the farm
for animal in farm:
print( animal )
print( '\n', '-' * 80 ,'\n' )
farm = [ ]
farm.append( "dog" ) # add a dog to it
farm.append( "cat" ) # then a cat
farm.append( "horse" ) # then a horse
farm.append( "pig" ) # and a pig
for animal in farm:
print( animal )
print( '\n', '-' * 80 ,'\n' )
farm = []
for i in range( 4 ):
animal = input( "Give me the name of an animal: " )
farm.append( animal )
for animal in farm:
print( animal )
print( '\n', '-' * 80 ,'\n' )
counter = 0
for animal in farm:
print( "animal #", counter+1, " : a ", animal, sep ='' )
counter = counter + 1
def main4():
print( '\n', '-' * 80 ,'\n' )
# start with four animals in the farm
farm = [ "horse", "pig", "dog", "cat" ]
# display the names of the animals
for animal in farm:
#print( animal )
print( "Old MacDonald had a farm, E-I-E-I-O" )
print( "And on his farm he had a", animal +", E-I-E-I-O" )
print( "Here a " + animal +", there a " + animal +", everywhere a "
+ animal + "!" )
print()
print( '\n', '-' * 80 ,'\n' )
# start with four animals in the farm
farm = []
for i in range( 4 ):
animal = input( "Give me the name of an animal: " )
farm.append( animal )
print( "\n" * 3 )
# display the names of the animals
for animal in farm:
#print( animal )
print( "Old MacDonald had a farm, E-I-E-I-O" )
print( "And on his farm he had a", animal +", E-I-E-I-O" )
print( "Here a " + animal +", there a " + animal +", everywhere a "
+ animal + "!" )
print()
main1()
main2()
main3()
main4()