user2775042
user2775042

Reputation: 509

caesar cipher problems in python

I have the following code which gives me error saying it cannot convert 'int' object to str implicitly. the if statements were used so if a letter in WORD is ascii 125 and i had to shift it by 5, I wanted the shift to goto ascii 32 and calculate. if any of the letters in word was less than ascii 32 shift, then shift to 32.

word=input("enter something to encrypt")
offset=int(input("Enter a number to shift it by"))
     for char in word:
        newword= ord(char)
        newword =newword+ chr(newword) + offset
        if newwword<32:
            result=result+95
        elif newword >126:
            result=result-95

Upvotes: 0

Views: 260

Answers (2)

DHandle
DHandle

Reputation: 402

The code you wrote is a little convoluted I'm afraid. A couple points though:

  • Your for loop should not be indented.
  • The "result" you calculate in the if-statements is not being used anywhere. I'm not sure this is intentional?

The error you are getting is from this line:

newword =newword+ chr(newword) + offset

newword is an integer prior to this statement, because ord(char) returns an integer.

Calling chr(newword turns that into a character... but then you try to add the offset (which is an integer) to that character.

Perhaps what you meant to do on this line is something more like newword = newword + chr(newword + offset)

HOWEVER, this will not yield you a caesar cipher of "word" as you are overwriting your previously shifted characters with the new characters each time you do the assignment here -> newword= ord(char)

Overall, I would perhaps suggest the following changes to your code:

word=input("enter something to encrypt")
offset=int(input("Enter a number to shift it by"))
newword = ""
for char in word:
    newchar = ord(char)
    newchar = newchar + offset
    if newchar < 32:
        newchar = newchar + 95
    elif newchar > 126:
        newchar = newchar - 95
    newword = newword + chr(newchar)
print("Encrypted word: " + newword)

Upvotes: 2

opatut
opatut

Reputation: 6864

Two problems:

1) You set newword every loop iteration, so you will never have the full result.

2) You compare the newword with an integer. You should maybe save the ord value, add the offset to it, compare that with 32 and 126, convert it back to a char using chr, then add it to the newword which you initialized with "" outside the loop, and after the loop print the newword. The order of all these steps does matter!

Upvotes: 0

Related Questions