0

「int」オブジェクトを暗黙的に str に変換できないというエラーが表示される次のコードがあります。if ステートメントが使用されたので、WORD の文字が ascii 125 であり、それを 5 シフトする必要がある場合、シフトを ascii 32 に移動して計算する必要がありました。Word の文字のいずれかが ASCII 32 シフト未満の場合は、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
4

2 に答える 2

2

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)
于 2013-09-15T01:49:11.000 に答える
0

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!

于 2013-09-15T01:45:53.397 に答える