0

I have to create these two functions for an assignment this week. I have the cipherIt function figured out, but the decipherIt function is erroring out with

num = int(num)-number TypeError: unsupported operand type(s) for -: 'int' and 'str'

and I'm not sure how to get the code to work.

cipherIt(word,number) - Converts and returns the word passed in to the function using a cipher. The cipher is to first convert the word to its Unicode equivalent and then add number. This function returns the unicode string (i.e. if word is "dog" and number is 5, it would return change it to "100-111-103", add 5 to each, and then return "105-116-108"

decipherIt(phrase,number) - Converts the phrase passed in to the function back to the original word by doing the reverse of the cipher above. (i.e. if phrase is "105-116-108" and number is 5, it would change it back to "100-111-103", and then convert that back to "dog")

def cipherIt(word, number):
    ans = ""
    for ch in word:
        num = ord(ch) + number
        ans += str(num) + "-"
    return ans[:-1]

def decipherIt(phrase, number):
    phrase = phrase.split("-")
    ans = ""
    for num in phrase:
        num = int(num)-number
        ans += chr(num)
    return ans

how the function is being called:

if __name__ == "__main__":
if len(sys.argv) < 2:
    print("Usage: python3 stringFunctions.py [function] <options>")
    print("Available Functions: ")
    print("foundIt, wordCount, hideIt, cipherIt, decipherIt, strongPassword")
    sys.exit(0)

elif sys.argv[1] == "decipherIt":
    if len(sys.argv) < 4:
        print("Usage: python3 stringFunctions.py decipherIt <phrase> <number>")
        print("Returns the real word by incrementing each number in phrase by number and converting them to characters")
        sys.exit(0)
    phrase = sys.argv[2]
    number = sys.argv[3]
    print(decipherIt(phrase, number))
  • How are you calling the function? Because it appears `number` is a `str` – Henry Ecker Apr 03 '22 at 02:23
  • It's an If Main with " elif sys.argv[1] == "decipherIt": if len(sys.argv) < 4: print("Usage: python3 stringFunctions.py decipherIt ") print("Returns the real word by incrementing each number in phrase by number and conv\ erting them to characters") sys.exit(0) phrase = sys.argv[2] number = sys.argv[3] print(decipherIt(phrase, number))" – Rebecca Krouse Apr 03 '22 at 02:24
  • Right so sys.argv is always going to give you string values (`str`). If `decipherIt` is expecting a number (`int`) you'll need to convert it first. For example, `number = int(sys.argv[3])` – Henry Ecker Apr 03 '22 at 02:32

0 Answers0