funcdemo.py

#!/usr/bin/env python
#
# Function Demo
# Write a table for arithmetic operations
#
# Author:  Yotam Medini  [email protected] -- Created: 2005/November/07
#

import sys

# Show how to use this program. No return value here
def usage(program_name):
    sys.stderr.write("Usage: %s <number> <operation>\n" % program_name)
    sys.stderr.write("Where operation is one of: '+' '-' 'X' '/' '%'\n")


# Compute :   x <op> y
def compute_operation(x, y, op):
    if op == '+':
        r = x + y
    if op == '-':
        r = x - y
    if op == 'X':
        r = x * y
    if op == '/':
        r = x / y
    if op == '%':
        r = x % y
    return r

# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# !!     Begin the program      !!
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

if len(sys.argv) != 1 + 2:
    usage(sys.argv[0])
    sys.exit(1)
    
n = int(sys.argv[1])
op = sys.argv[2]
if not op in ['+', '-', 'X', '/', '%']:
    sys.stderr.write("Bad op: '%s'\n" % op)
    usage(sys.argv[0])
    sys.exit(1)

sys.stdout.write(" %d X %d   %s Table\n\n" % (n, n, op))

# The 1st row, with x values.
sys.stdout.write("%s  x |" % op)
x = 1
while x <= n:
   sys.stdout.write(" %3d " % x)
   x = x + 1
sys.stdout.write("\n")
# The 2nd boring row.
dash_line = n*5*'-' # -------------------- of good length
sys.stdout.write("y     " + dash_line + "\n")

# Now the table itself. Left column with y values!
y = 1
while y <= n:
    sys.stdout.write("%3d  |" % y)
    x = 1
    while x <= n:
        xopy = compute_operation(x, y, op)
        sys.stdout.write(" %3d " % xopy)
        x = x + 1
    sys.stdout.write("\n")
    y = y + 1
sys.exit(0)


Generated by GNU enscript 1.6.4.