Contents

  1. binaryToDecimal.test.py
  2. file_handle.py
  3. loop.py
  4. therapist.py
  5. while.py
  6. whilevsfor.py
  7. yearborn.py

binaryToDecimal.test.py 1/7

[
top][prev][next]
# Converts a binary number into a decimal
# Modify to verify that the inputted number is valid.
# 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(binary[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

def testIsBinary():
    """
    Test the isBinary function.
    Displays the correctness or incorrectness of the function.
    Does not return anything.
    """
    
    testBinaryTrue = ["10", "0", "0000", "01", "1000010"]
    
    for test in testBinaryTrue:
        result = isBinary(test)
        if result:
            print(test, "successfully identified as binary")
        else:
            print("**ERROR! **", test, "considered not binary")
    
    testBinaryFalse = ["10a", "0000z", "1O", "O"]
    
    for test in testBinaryFalse:
        result = isBinary(test)
        if not result:
            print(test, "successfully identified as not binary")
        else:
            print("**ERROR! **", test, "considered binary")

def testBinaryToDecimal():
    """Test the binaryToDecimal function.  
        Displays the correctness or incorrectness of the function.
        Nothing is returned."""
    testInput = "10"
    expectedResult = 2
    actualResult = binaryToDecimal(testInput)
    if actualResult != expectedResult:
        print("**ERROR! **", testInput, "should be", expectedResult)
        print("Instead, got", actualResult)
    else:
        print("Success on binary to decimal for", testInput, "-->", actualResult)
            
testIsBinary()
testBinaryToDecimal()            

file_handle.py 2/7

[
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")
        inFile.close() # not doing anything with the file, so closing it immediately
    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() # not doing anything with the file so closing it immediately
    except IOError as exc:
        print("Error writing \"" + outfileName + "\".")
        print(exc)
    
main()

loop.py 3/7

[
top][prev][next]
# What does this loop do?
# Sara Sprenkle

count = 1
while count > 0:
	print(count)
	count += 1

therapist.py 4/7

[
top][prev][next]
# The Simple Therapist
# CSCI 111

print("-"*60)
print("Welcome to computerized therapy!")
print("You will get your money's worth.")
print("Our session is over when you have nothing more to tell me.")
print("-"*60)

user_input = input("Tell me what's wrong.\n")

while user_input != "":
    user_input = input("How does that make you feel?\n")

print("Thank you!  Come again!")

while.py 5/7

[
top][prev][next]
# Demonstrates a simple while loop
# Sara Sprenkle

i = 0
while i < 10 :
    print("i equals", i)
    i+=1
print("Done", i)


whilevsfor.py 6/7

[
top][prev][next]
# Compares a while loop with a for loop
# by Sara Sprenkle

# ---------- WHILE LOOP ----------

print("While Loop Demo")
i=0
while i < 10:
    print("i equals", i)
    i += 1
print("Done", i)

# ---------- FOR LOOP ----------

print("\nFor Loop Demo")
for i in range(10):
    print("i equals", i)

print("Done", i)
# To give exactly the same output as the while loop, would need to print out i+1


yearborn.py 7/7

[
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 = eval(input("Enter your age: "))
        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.4.