我正试图使用循环和if/elif
在python中制作一个凯撒密码加密程序,但我的程序返回了不想要的结果。我的编程逻辑可能有一个小错误,也许有人想帮我修复它
此输入:
caesar
2
并且应该显示输出:
ecguct
但我的程序显示输出:caesar #thats wrong
这是我正在尝试的代码:
x = []
ch = ""
i = 0
x = input(" enter words : ")
y = int(input("enter number : "))
for i in range(len(x)):
i+1
ch = x[i]
if(ord(ch)>=ord('a') and ord(ch)<=ord('z')):
chr(ord(ch)+y)
elif(ord(ch)>ord('z')):
(ord(ch)- ord('z')-ord('a')-1)
x[i]=ch
elif(ord(ch)>=ord('A') and ch<=ord('Z')):
chr(ord(ch)+y)
elif(ord(ch)>ord('Z')):
(ord(ch)- ord('Z')+ord('A')-1)
x[i]=ch
print(x)
我对我制作的i+1
和x[i]=ch
的迭代感到不确定——这是正确的语法吗?。此外,我使用ord()
将值字符串更改为整数。我需要你的意见来解决它。
您的代码中有几个错误。首先,您必须使用chr()
函数再次将计算转换为char。有时你会,有时你不会。那么你就不能索引字符串了——这里是x[i]=ch
。相反,您必须使用+=
运算符或其他append
方法将结果分配给一个新字符串。最后,您的if
和elif
没有覆盖它应该覆盖的溢出。如果您输入的字符串包含字母y
、z
、Y
或Z
,它将溢出。覆盖这些溢出的if
问题需要嵌套在处理不同大小写字母的顶级if
-elif
中
溢出计算中还有一个小错误,即使用-
减号运算而不是+
加号运算
这是您代码的稍微固定的版本:
x = input(" enter words : ")
y = int(input("enter number : "))
y = y % 26 # limit y to the amount of possible letters
result = ""
for ch in x:
if(ch>='a' and ch<='z'):
ch = chr(ord(ch)+y)
if(ch>'z'):
ch = chr(ord(ch)- ord('z')+ord('a')-1)
elif(ch>='A' and ch<='Z'):
ch = chr(ord(ch)+y)
if(ch>'Z'):
ch = chr(ord(ch)- ord('Z')+ord('A')-1)
result += ch
print("input:", x)
print("output:", result)
您还可以像"for ch in x
"那样直接迭代字符串的字母,而不需要使用x[i]
进行额外的索引。字符比较不需要ord(...)
函数
进一步缩小:
x = input(" enter words : ")
y = int(input("enter number : "))
result = "".join ( [ [ # encrypting a string by adding a number to all letters
c, chr((ord(c)-ord('Aa'[c.islower()])+y)%26+ord('Aa'[c.islower()]))
] [ c.isalpha() ] for c in x ] )
print("output:", result)
这段代码更难阅读,应该包含一些关于它实际功能的注释。如果你有更多的代码,缩小可能会让你更容易理解,因为否则你在一个项目中会有大量的文件和模块。