As the title suggests, I have a "TypeError: not all arguments converted during string formatting" error in vigenere.py for Pset6.

Here's the code:

import cs50
import sys

if len(sys.argv) == 1 or len(sys.argv) > 2:
    print("Usage: python vigenere.py <key>")

key = sys.argv[1]
for i in range(len(key)):
    if key[i].isalpha() is not True:
        print("Keyword must only contain letters A-Z or a-z")

print("plaintext: ", end="")
plaintext = cs50.get_string()
plaintext_size = len(plaintext)
key_size = len(key)
ciphertext = []
for i in range(plaintext_size):
    j = 0
    if j >= key_size:
        j = 0
    if plaintext[i].isalpha():
        k = key[j].upper() % 65
        c = plaintext[i] + k
        if ord(plaintext[i].upper()) + k > ord('Z') or ord(plaintext[i].lower() + k > ord('z')):
            c = c - 26
        j = j + 1
        ciphertext[i] = plaintext[i]

print("ciphertext: ", end="")

Any help would be appreciated. Thanks.


On this line:

k = key[j].upper() % 65

The % operator in Python does different things depending on whether the left operand is a number or a string. If it's a number, then % does modulo division as in C (with the added feature that Python's modulo also works with floats). If it's a string, however, % performs string formatting, filling a similar role as the sprintf function from C. Details on this formatting operation can be found here.

Additionally, whereas a char in C is effectively a kind of number, and can be used in arithmetic, there's no such implicit equivalence between ints and single-character strings in Python. Instead, you'll want to use the ord function.

P.S. When asking for help with an error message, it's helpful to point out which line Python says is causing the error.

  • It's line 24, the one with the string formatting error I made. Thanks for pointing that out, by the way. Should I pass key[j].upper() as an argument to ord(), then? Taking the remainder of that with the modulus operator should have the intended effect, right? – Osman Zakir Feb 21 '17 at 22:32
  • Yes, that sounds right. – Levi Roth Feb 22 '17 at 1:07
  • Okay, so I got that fixed. But now there's a logic error, and I think it's on lines 26 and 27. I put the code on Pastebin here: pastebin.com/iwqrjqKY. Wherever else you see an error, please point it out. Thanks. – Osman Zakir Feb 22 '17 at 10:21

You must log in to answer this question.

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