CSC Nested-Loop Exercises Solution Programs

From dftwiki3
Revision as of 07:28, 29 September 2011 by Thiebaut (talk | contribs) (Created page with "--~~~~ ---- <source lang="python"> # Solutions to exercises # print( "\n\n\n" ) cards = [ "As", "King", "Queen", "Jack" ] for card in cards: print( "Card = ", card ) ...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut 08:28, 29 September 2011 (EDT)


# Solutions to exercises
# 
print( "\n\n\n" )

cards = [ "As", "King", "Queen", "Jack" ]
for card in cards:
      print( "Card = ", card )
      cards.append( card )

# the above loop is infinite.  An infinite loop

print( "\n\n\n" )
# square of stars
for i in range( 4 ):     # 4 lines
    # print a line of 5 stars, no \n at the end
    for j in range( 5 ):
        print( '*', sep='', end='' )

    # go to the next line
    print()

print( "\n\n\n" )
# triangle of stars

for i in range( 5 ):        # 5 lines
    for j in range( i+1 ):  # when i==0, we want 1 star
        print( '*', sep='', end='' )
    print()

print( "\n\n\n" )
# triangle of stars, bottom up
for i in range( 5 ):
    # print a line of stars, 5 when i is 0
    for j in range( 5-i ):
        print( '*', sep='', end='' )
    print()

print( "\n\n\n" )
# a rectangle of numbers
for i in range( 3 ):
    for j in range( 6 ):
        print( j, sep=' ', end='' )
    print()


print( "\n\n\n" )
# another square of numbers
for i in range( 3 ):
    for j in range( 5 ):
        print( i+j, sep='', end='' )
    print()

print( "\n\n\n" )
# all the characters of the alphabet
for c in "abcdefghijklmnopqrstuvwxyz":
    print( c )


print( "\n\n\n" )
# some account numbers
for c in "abcdefghijklmnopqrstuvwxyz":
    print( "111a-a" + c )

print( "\n\n\n" )
# all the account number in the class
for first in [ 'a', 'b' ]:
    for second in "abcdefghijklmnopqrstuvwxyz":
        print( "111a-" + first + second )

print( "\n\n\n" )
# all the account number in the department
for course in [ '111', '231', '240', '274' ]:
    for first in [ 'a', 'b' ]:
        for second in "abcdefghijklmnopqrstuvwxyz":
            print( course + "-" + first + second )
    print()