简体   繁体   中英

Python Caesar Cipher style program: Why does python give me TypeError of unsupported operand type(s)?

I am working on a project and am on my final stage of my project, but stuck on this error:

Secret message: hello
shift: 4

Traceback (most recent call last):
File "program.py", line 5, in <module>
next_code = code + str(move)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

I have tried alternate solutions to this, but the plus sign is really bothering me. I am not too good at this stuff since i am a beginner, so i need some help, and i would also like to know how to make it that only uppercase characters are switched, and not the symbols. Here is my code:

ask = input("Secret message: ")
move = input("shift: ")
for i in ask:
code = ord(i)
next_code = code + str(move)
next_character = chr(next_code)
print(next_character)

Why am i getting this and what is my problem? Thanks in advance!

You need to convert move to an integer, not a string, when adding it to ord(i)

next_code = code + int(move)

However, as you point out in your question, this will just shift all the characters in your message along the values in the ASCII table, rather than shifting the alphabetic characters along the alphabet.

You could change your method to use a string of the uppercase alphabet like that in the caesar cipher tutorial in Al Sweigart's python ciphers ebook.

You could also adjust your code to check whether a character is a letter before encrypting. The uppercase alphabet are values 65-90 in the ASCII table.

if 65 <= code <= 90:
    # encrypt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM