我是新手,刚接触编程领域。在完成cs50的凯撒密码练习时,遇到了Python的问题,但我无法弄清楚出了什么问题。非常感谢您的帮助!
from cs50 import get_string
from sys import argv
if len(argv) != 2:
print("only input one integer")
x = argv[1]
n = get_string("plaintext: ")
for i in range(len(n)):
if str.islower(n[i]):
lower = (((ord(n[i]) - 97 + x) % 26)) + 97
print(chr(lower), end="")
elif str.isupper(n[i]):
upper = (((ord(n[i]) - 65) + x) % 26) + 65
print(chr(upper), end="")
else:
print(f"{n[i]}", end="")
在终端窗口中,预计会出现以下内容:
python caesar.py 1
plaintext: hi
ij
但是它说:
Traceback (most recent call last):
File "caesar.py", line 14, in <module>
lower = (((ord(n[i]) - 97 + x) % 26)) + 97
TypeError: unsupported operand type(s) for +: 'int' and 'str'
+
运算符应用于字符串和数字会导致错误(您正在遇到的错误)。要么将数字转换为字符串(以进行连接),要么将字符串转换为数字(以进行加法)。 - dcg