Debugging for a newbie


#1

Hi there,

I am completely new to Python and have taken over a class midway through their course. I am myself learning using the Computer Science Circles Course but i have run into a problem that I can't help a student with at my level of experience. I know in principle what the problem is but I am having difficulty crafting a solution.
Problem is read a file, working, encrypt the file, save and generate an 8 character key working, enter key and decrypt the new file not working. The file uses an offset to encrypt to ASCII characters.
Code below:
try:
print("Welcome to encryption")
print("Please Select an operation")
print("1. Encryption")
print("2. Decryption")
print("3. Terminate Program")

users Choice of operation

choice = input("ENTER YOUR CHOICE (1/2/3): ")

def encrypt():
    file = input("enter you file name: ")
    print("Key:")
    keytotal = 0
    key = []
    OF = 0
    for v in range(0,8):
        num = random.randint(33,126)
        keytotal = keytotal + num
        key.append(chr(num))
        print(key[v],end="")

    fo = open(file,"r+")
    fo = fo.read()
    print(" ")
    #offset factor
    OF = math.floor(keytotal/8)-32
    print("Offset Factor:")
    print(OF)
    
    s = [ord(i) + OF for i in fo]
    for length in range(0, len(s)):
        if s[length] == 32 + OF:
            s[length] = s[length] - OF
        elif s[length] > 125:
            s[length] = s[length] - 94
    encrypted = [chr(i) for i in s]
    final = ''.join(encrypted)

    FF = input("What Would You Like To Save Your Encription As?: ")
    nf = open(FF,"a+")
    nf.writelines(final)
    nf.close()
    
            
def decrypt():
    file = input("enter you file name: ")
    fo = open(file,"r+")
    fo = fo.read()
    print(" ")
    OF = 0
    key = []
    s = 0
    #finding the offset factor
    key  = input("enter your 8 digit key: ")
    
    for x in key:
        OF=OF+ord(x)
    OF = (math.floor(OF*8)+32)
    
    s = [ord(i) + OF for i in fo]
    for length in range(0, len(s)):
        if s[length] == 32 - OF:
            s[length] = s[length] + OF
        elif s[length] > 32:
            s[length] = s[length] + 94
    encrypted = [chr(i) for i in s]
    final = ''.join(encrypted)
    
    FF = input("What Would You Like To Save Your Encryption As?: ")
    nf = open(FF,"a+")
    nf.writelines(final)
    nf.close()
    
    
        
    
    
if choice == "1":
    encrypt()
    
elif choice == "2":
    decrypt()

elif choice == "3":
    exit()

except ValueError:

#print("try again")