PTA 凯撒密码 python解决

(凯撒密码)是一个简单的替换加密技术,它简单地将明文字符串中的全部字母在字母表上偏移n项。当n大于0时,表示向后偏移,小于0则表示向前偏移。当n为2时,字母A变C,c变e,y变a, Z变B;当n为-2时,字母A变Y,c变a,y变w,Z变X。请编写程序,依次读入明文字符串及整数偏移量n,然后输出加密后的密文字符串。提示:C语言可用gets()函数,C++语言可用getline()函数读入整行字符串。

样例">样例">样例">样例">输入样例:

No One Can Stop Us
2

输出样例:

Encrypted message:Pq Qpg Ecp Uvqr Wu

考虑一下的情况:①n>26或n<-26②上越界,如Z偏移3③下越界,如a偏移-2.

完整代码:

a=input()
n=int(input())
N=abs(n)%26
print("Encrypted message:",end="")
for i in range(len(a)):
    if 65<=ord(a[i])<=90:
        if n>=0 and ord(a[i])+N>90:
            print(chr(ord(a[i])+N-26),end="")
        elif n>=0 and ord(a[i])+N<=90:
            print(chr(ord(a[i])+N),end="")
        elif n<0 and ord(a[i])-N<65:
            print(chr(ord(a[i])-N+26),end="")
        elif n<0 and ord(a[i])-N>=65:
            print(chr(ord(a[i])-N),end="")
    elif 97<=ord(a[i])<=122:
        if n>=0 and ord(a[i])+N>122:
            print(chr(ord(a[i])+N-26),end="")
        elif n>=0 and ord(a[i])+N<=122:
            print(chr(ord(a[i])+N),end="")
        elif n<0 and ord(a[i])-N<97:
            print(chr(ord(a[i])-N+26),end="")
        elif n<0 and ord(a[i])-N>=97:
            print(chr(ord(a[i])-N),end="")
    else:
        print(a[i],end="")

你可能感兴趣的:(PTA解答,python,java,开发语言)