Comp 150 – Computer Programming 1

January 30, 2008

 

 

1.         Decimal to Hexadecimal Digit Conversion

 

#

#  Name:

#  File: DigitConversionSp08.py

#  Date: January 30, 2008

#

#  Desc: Converts Decimal Digits to Hexadecimal

#

 

def main():

 

    # Display Title

 

    print

    print "Decimal to Hexadecimal Digit Conversion"

    print

 

    #  Use a string to list the hexadecimal digits

 

    hexDigits = "0123456789ABCDEF"

 

    #  Get decimal value

   

    n = input("Enter a decimal digit between 0 and 15: ");

 

    #  look up hex value and display it

   

    print

    print n, "=", hexDigits[n]

    print

   

main()   

 

2.         Caesar Cipher Program

 

#

#  Name:

#  File: CaesarCipher.py

#  Date: January 30, 2008

#

#  Desc: An implementation of the Caesar cipher

#

 

def main():

 

    # Display Program Title

   

    print

    print "Caesar Cipher Program"

    print

 

    # Get Plain Text String and Numeric Key

   

    str1 = raw_input("Enter plain text to encode: ")

    key = input("Enter key: ")

 

    # Generate Cipher Text String 

 

    str2 = ""                           # initialize cipher text str to empty

    for i in range(len(str1)):

        a = (ord(str1[i])- ord("A"))    # Convert letter to integer value

                                        #     between 0 and 25

        b =((a + key) % 26)             # Apply numeric key

        c = chr(b + 65)                 # Convert integer to ASCII char

        str2 = str2 + c                 # concatenate to cipher text string

 

    #  Display Cipher Text String

   

    print

    print "Cipher text:", str2

 

    #  Decode Cipher Text

 

    reversedKey = 26 - key              # adding 26 - key is equivalent

                                        #    to subtracting key

    str3 = ""                           # initialize decoded text string

    for i in range(len(str2)):

        a = (ord(str2[i])- ord("A"))    # letter -> range(25)

        b =((a + reversedKey) % 26)     # apply reversed numeric key

        c = chr(b + 65)                 # convert to ASCII character

        str3 = str3 + c                 # concatenate to decoded string

 

    #  Display Decoded Text

   

    print

    print "Decoded Cipher Text:", str3

    print

 

main()