Vigenere cipher in python

1.5k Views Asked by At

Writing a vigenere cipher in python and I've got completely lost in it, anyone fancy giving me a hand and suggesting things that could be improved/make it work correctly? Currently I'm getting all sorts of errors

letters='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
print ("This program will take a keyword, and use it to encrypt plaintext.")
def keyword():
    print ("Please enter your keyword")
    keyword = input()
    return keyword

def plaintext():
    print ("Please enter your plaintext")
    plaintext = input()
    return plaintext

def translate (keyword, plaintext):
    keywordtwo=0
    number=0
    keyword=keyword.upper()
    length = len(plaintext)
    lengthtwo=len(keyword)
    for symbol in plaintext:
        number=letters.find(symbol.upper())
        if number!=-1:
            number+=letters.find
        num%=len(letters)
        if symbol.isupper():
            translated.append(letters[number])
        elif symbol.islower():
            translated.append(letters[number].lower())
        if keywordtwo==len(keyword):
           keywordtwo=0
    else:
        translated.append(symbol)
    return ' '.join(translated)




keyword = keyword()
plaintext = plaintext()
translated = translate(keyword, plaintext)

print ("Your new text is:")
print (translate(keyword, plaintext))
1

There are 1 best solutions below

0
On

TypeError: unsupported operand type(s) for +=: 'int' and 'builtin_function_or_method' refers to the code at line 22: number+=letters.find.

number is an int (number) and letters.find is a method (a built-in method), and you're trying to add those together. That's not going to work. What you probably intended to do was to call that function, which looks like number += letters.find(...), where ... stands for whatever letter you want to look up.

The next error you'll get will be something like UnboundLocalError: local variable 'num' referenced before assignment. That's on line 23: number%=len(letters). num does not exist, I assume you meant number instead.

Then you'll get NameError: global name 'translated' is not defined, which refers to line 31: translated.append(symbol). You're trying to add an item to a list named translated, but translated does not exist at that point (you do define it further down, outside your translate function, but even then, you should use a local variable, not a global one). Add translated = [] to the start of your translate function.