CSC111 Homework 6 Solution 2014
Revision as of 09:46, 26 March 2014 by Thiebaut (talk | contribs) (Created page with "--~~~~ ---- There were several good solution programs for Homework 6. You were not required to use a '''main()''' function, although some...")
--D. Thiebaut (talk) 09:46, 26 March 2014 (EDT)
There were several good solution programs for Homework 6. You were not required to use a main() function, although some did. The program below is a good example of how Python programs should be organized, with a header first, possibly a few import statements, maybe a constant or two, then a long list of function definitons (def statements), then the definition of the main() function, and at the very end, one call to main() that starts the whole program.
Program 1
# Program: hw6a.py
# Programmer: Yumeng Wang(cf)
# (slightly edited by D. Thiebaut)
# The last edited time: 03/11/2014
# The program asks the user for an input which needs
# to be an integer that is greater or equal to 0,
# and then displays a chessboard with that dimension
# while each cell of the chessboard is represented by a
# 3*3 block.
# --------------------define functions---------------------
# printElement( visibility )- shows how to print one 1*3
# element in a 3*3 block.
def printElement( visibility ):
if visibility == True:
print( "###", end="" )
else:
print( "...", end="" )
# printOneLine( visibility )- print the first line of each row
def printOneLine( dimension, visibility ):
# it prints"###" and "..." one by one until
# the number of them is equal to the dimension
for i in range ( dimension ):
printElement( visibility )
visibility = not visibility
# when dimension is odd, change the visibility after
# it prints a line so that we have the original visibility
# at the beginning of every new line.
if dimension % 2 != 0:
visibility = not visibility
# printThreeLine( visibility )- print one row by print
# the same line three times.
def printThreeLine( dimension, visibility ):
for i in range (3):
printOneLine( dimension, visibility )
print()
# printBoard( visibility)- print the whole chessboard
# by printing the required number(dimension) of rows.
def printBoard( dimension, visibility ):
for i in range ( dimension ):
printThreeLine ( dimension, visibility )
visibility = not visibility
# ==================================================================
# MAIN PROGRAM
# ==================================================================
# main()- set the visibility to be true and print the
# printBoard( visibility ) function.
def main( ):
# get dimension from user
dimension = int(Input("Enter dimention of board: "))
while dimension < 0:
dimension = int(Input("Enter dimention of board: "))
printBoard( dimension, True )
main()
Program 2