from cs50 import get_string

from sys import argv import sys

def main ():

Vigenere enciphering program

#define variables
key = str.lower (sys.argv[1])       # catch the key from command line and convert it to lowercase
key_index = 0                       # set the key index for iterating through the key
key_length = len(key)               # determine the length of the string

key_arr = key[key_index % key_length]  # I think I want the letters in key to appear in a list

#check proper usage, for command line and key validity
while True:
    if len(argv) != 2 or str.isalpha(key) == False:
        print('Usage: python vigenere.py k')
        return 1
    # When the submitted key is valid    

        # Get plaintext from user
        plaintext = get_string('PLAINTEXT: ')
        print('You entered: ',plaintext)                        # for testing remove later
        # find the length of the plaintext string
        plaintext_length = len(plaintext)
        print('the length of the plaintext is: ',plaintext_length)      # for testing remove later
        key_letter = ord(key_arr[key_index % key_length] - 97)          # line 34 - unsupported operand type(s) for -: 'str' and 'int'

As above, I'm trying to use key_letter as a list of ASCII characters constructed from the key entered by the user. I am getting an 'unsupported operand type' error on the last line in the segment above (line 34). Eventually I plan use key_letter in this equation:

                  enciphered = ((key_letter + ascii_i - 65) % 26) + 65    #encipher i with current key_letter

How can I better set up key_letter to behave in the way I want? Thank you.

1 Answer 1


ord(key_arr[key_index % key_length] - 97) needs to be ord(key_arr[key_index % key_length]) - 97, performing the subtraction after conversion to ASCII value.

You should check len(argv) before accessing argv[1], it might not exist.

I don't get your key_arr variable, it's set to the first character of your string. You can use key, strings are subscriptable, just like in C, so the correct way would be more like ord(key[key_index % key_length]) - 97.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .