Contents

  1. binaryToDecimal.py
  2. file_handle.py
  3. oldmac.py
  4. palindrome.py
  5. palindrome_refactored.py
  6. pick4num_wfunctions.py
  7. testingBinaryToDecimal.py
  8. yearborn.py

binaryToDecimal.py 1/8

[
top][prev][next]
# Converts a binary number into a decimal
# Modify to verify that the inputted number is valid.
# Added test functions that programmatically test if the function is behaving
# appropriately.
# By CSCI111

import sys

def main():
    # Read in the binary number as a string -- why?
    num = input("Enter the binary #: ")
    
    # --------- Validate the user input ----------
    if not isBinary(num):
        print(num, "is not a valid binary number.  Please try again.")
        sys.exit()
        
    decVal = binaryToDecimal(num)
    
    print("The decimal value for", num, "is", decVal)


def binaryToDecimal(binnum):
    """
    Converts the binary number to a decimal number
    Precondition: binary, a string that is a binary number
    Postcondition: returns the decimal value of the binary number
    """
    # accumulate the decimal value in this variable
    decVal = 0
    
    # go through the positions in the string
    for pos in range(len(binnum)):
        # num[pos] is a string; need to convert to an int
        bit = int(binnum[pos])
        # calculate which "place" the current bit is at
        place = 2**(len(binnum)-pos-1)
        # add to the decimal value
        decVal += place * bit
    return decVal

    
def isBinary(candidate):
    """
    Precondition: candidate is a string
    Postcondition: returns True iff candidate is a valid binary string
    """
    # check that it has all digits (no letters)
    if not candidate.isdigit():
        return False
     
    # Make sure that the inputted number only contains 0s and 1s
    for digit in candidate:
        if digit != "0" and digit != "1":
            return False
    return True


file_handle.py 2/8

[
top][prev][next]
# Demonstrate file handling exception
# Sara Sprenkle

import sys

def main():
    infileName = input("What file do you want to read? ")
    
    try:
        inFile = open(infileName, "r")
        # normally, would be doing some sort of processing of the file here.
        inFile.close()
    except IOError as exc: # exc is the name of the thrown exception
        print("Error reading \"" + infileName + "\".")
        # could be a variety of different problems, so print out
        # the exception
        print(exc)
        sys.exit(1)

    outfileName = input("What file do you want to write? ")
   
    try:
        outFile = open(outfileName, "w")
         
        outFile.close()
    except IOError as exc:
        print("Error writing \"" + outfileName + "\".")
        print(exc)
    
main()

oldmac.py 3/8

[
top][prev][next]
# Print out verses of the song Old MacDonald
# Sara Sprenkle

BEGIN_END = "Old McDonald had a farm"
EIEIO = ", E-I-E-I-O"

def main():
    # call the verse function to print out a verse
    printVerse("dog", "ruff")
    printVerse("duck", "quack")
    
    animal_type = "cow"
    animal_sound = "moo"
    
    printVerse(animal_type, animal_sound)
    

def printVerse(animal, sound):
    """
    prints a verse of Old MacDonald, plugging in the animal and sound
    parameters (which are strings), as appropriate.
    """
    print(BEGIN_END + EIEIO)
    print("And on that farm he had a " + animal + EIEIO)
    print("With a " + sound + ", " + sound + " here")
    print("And a " + sound + ", " + sound + " there")
    print("Here a", sound)
    print("There a", sound)
    print("Everywhere a " + sound + ", " + sound)
    print(BEGIN_END + EIEIO)
    print()

if __name__ == '__main__':
    main()
#main()

palindrome.py 4/8

[
top][prev][next]
# Determines if a phrase is a palindrome
# 

print("This program determines if a given phrase is a palindrome,")
print("ignoring spaces and the case of letters.\n")
    
phrase=input("What is your phrase? ")

lowerPhrase=phrase.lower()
lphrasenospace=lowerPhrase.replace(" ","")

end=len(lphrasenospace)

phrase_backwards=""

for x in range(end-1,-1,-1):
    phrase_backwards=phrase_backwards+lphrasenospace[x]
    
   
if phrase_backwards==lphrasenospace:
    print(phrase, "is a palindrome")
else:
    print(phrase, "is not a palindrome")

palindrome_refactored.py 5/8

[
top][prev][next]
# Determines if a phrase is a palindrome
# 

def main():
    print("This program determines if a given phrase is a palindrome,")
    print("ignoring spaces and the case of letters.\n")
        
    phrase=input("What is your phrase? ")
    
    isitapalindrome = isPalindrome(phrase)
    
    if isitapalindrome == True:  # if isPalindrome(phrase):
        print(phrase, "is a palindrome")
    else:
        print(phrase, "is not a palindrome")

def isPalindrome(phrase):
    """
    """
    lowerPhrase=phrase.lower()
    lphrasenospace=lowerPhrase.replace(" ","")
    
    end=len(lphrasenospace)
    
    phrase_backwards=""
    
    for x in range(end-1,-1,-1):
        phrase_backwards=phrase_backwards+lphrasenospace[x]
       
    if phrase_backwards==lphrasenospace:
        return True
    else:
        return False
    # return phrase_backwards==lphrasenospace

pick4num_wfunctions.py 6/8

[
top][prev][next]
# Simulate Pick 4 lottery game - selecting ping pong balls at random
# Modified to figure out if the user entered the winning number
# By CSCI111

from random import *
import sys

# define constants that are easy to change so that our
# program is flexible
NUM_PICKS = 4
MIN_VALUE = 0
MAX_VALUE = 9

NUMFORMAT="####"

def main():

    pickedNum = input("What is your pick? (Format: " + NUMFORMAT + ") ")
    
    ######  handle bad input ######
    error = False
    errorMessage = "Error:\n"
    
    # Check that user enters a string that contains only numbers
    if not pickedNum.isdigit():
        errorMessage += "\tYour number must contain only numbers\n"
        error = True
    
    # User enters a number that is not four digits long
    if len(pickedNum) != 4:
        errorMessage += "\tYour number must contain four numbers"
        error = True
        
    if error:
        print(errorMessage)
        sys.exit()
    
    winningNum = generateWinningNum()
    
    print("The winning Pick 4 lottery number is ", winningNum)
    print()
    
    if winningNum == pickedNum:
        print("Congratulations!  You are very lucky and rich!")
        print("We should be friends!")
    else:
        print("Sorry, you lost.")
    
def generateWinningNum(numNums=NUM_PICKS):
    """
    generates a winning number based on constants defined for ...
    returns a string of random numbers of length numNums; 
    default numNums is NUM_PICKS
    """
    # Generate the random number
    winNum = "" # start it as empty
    
    for i in range(numNums):
        # generate a random number
        # add the random number to the previous random number
        winNum += str(randint(MIN_VALUE,MAX_VALUE))
        
    return winNum
    
main()

testingBinaryToDecimal.py 7/8

[
top][prev][next]
# Demonstrates how we can include other's code in our code
# by importing them as modules.

from binaryToDecimal import *

def testIsBinary():
    """
    Test the isBinary function.
    Displays the correctness or incorrectness of the function.
    Does not return anything.
    """
    
    # ----------- Test where the result should be True ---------

    testBinaryTrue = ["0", "1", "10", "1001", "10000"]
    
    for test in testBinaryTrue:
        result = isBinary(test)
        if result:
            print(test, "successfully identified as binary")
        else:
            print("**ERROR! **", test, "considered not binary")
    
    # ----------- Test where the result should be False ---------
    testBinaryFalse = ["a", "3", "-100", "123"]
    
    for test in testBinaryFalse:
        result = isBinary(test)
        if not result:
            print(test, "successfully identified as not binary")
        else:
            print("**ERROR! **", test, "considered binary")
    
    # ------------ Alternatively, have a list of inputs and expected ----
    # Question: How difficult is it to verify additional test cases?
    inputs = [ "0", "1", "10", "1001", "10000", "a", "3", "-100", "123"]
    expectedResults = [ True, True, True, True, True, False, False, False, False]
    for pos in range(len(inputs)):
        testInput = inputs[pos]
        if isBinary(testInput) != expectedResults[pos]:
            print("Error on isBinary(", testInput, ")")
            print("Expected", expectedResults[pos], "but got", isBinary(testInput))
    

def testBinaryToDecimal():
    """Test the binaryToDecimal function.  
        Displays the correctness or incorrectness of the function.
        Nothing is returned."""
        
    paramInputs = ["0", "1", "10", "1001", "10000"]
    expectedResults = [ 0, 1, 2, 9, 16]
    for index in range(len(paramInputs)):
        paramInput = paramInputs[index]
        expectedResult = expectedResults[index]
        actualResult = binaryToDecimal(paramInput) 
        if actualResult != expectedResult:
            print("**ERROR! **", paramInput, "should be", expectedResult)
            print("Instead, got", actualResult)
        else:
            print("Success on binary to decimal conversion for", paramInput, "-->", actualResult)
            
testIsBinary()
testBinaryToDecimal()            

yearborn.py 8/8

[
top][prev][next]
# Demonstrate validating user input
# Modified from a student's code from lab assignment

import sys

def main():
    #Program mission statement
    print("This program determines your birth year")
    print("given your age and the current year \n")

    try:
        age = int(input("Enter your age: "))
        # note difference if use eval instead of int in above 
        currentyear = int(input("Enter the current year: "))
    except:
        print("ERROR: Your input was not in the correct form.")
        print("Enter integers for your age and the current year")
        sys.exit()
    
    if age < 0 or age > 115:
        print("Come on: you have to be a reasonable age.")
    elif currentyear < 0:
        print("You need to have a positive year.")
    else:
        #Subtract age from current year
        birthyear=currentyear - age
        #Display output to the user
        print("You were either born in", birthyear, "or", birthyear-1)


main()

Generated by GNU Enscript 1.6.6.