≡ Menu

Prepulator

A toy program for demonstrating Python functions:

#==============  readChoice ==============  
def readChoice():

    choice = "bogus"
    while choice not in("S", "D", "R", "N", "E"):
        #**** Functions can invoke other functions. Here we're invoking the print() function.
        print("********************************")
        print("(S)quare")
        print("(D)ouble")
        print("(R)eciprocal")
        print("(N)egate")
        print("(E)xit")
        choice = input('Choose from the functions above: ').upper()

    return(choice)

#==============   readX ==============
def readX():

    hasGoodX = False
    while not(hasGoodX):
        try:
            x = int(input('Enter your x: '))
            hasGoodX = True
        except ValueError:
            print("Try again. x must be an integer.")

    return(x)

#==============  printResult ==============
#****** Functions can accept many arguments. Here we're accepting a string and 2 integers.
def printResult(funcName, originalX, result):
    print("The " + funcName + " of " + str(originalX) + " is " + str(result) + ".")

#==============   square ==============
def square(x):
    return x * x

#==============   double ==============
def double(x):
    return x + x

#==============   reciprocal ==============
def reciprocal(x):
    return 1/x

#==============   begin main program ==============
choice = "not E"
while(choice != "E"):
    choice = readChoice()
    if (choice != "E"):
        x = readX()

    if (choice == "S"):
        printResult("square", x, square(x))
    elif (choice == "D"):
        printResult("double", x, double(x))
    elif (choice == "R"):
        printResult("reciprocal", x, reciprocal(x))
    elif (choice == "N"):
        print("Rats! I forgot to implement Negate. Why don't you try it?")