我的凯撒为何不能正常工作?

时间:2013-08-16 07:15:09

标签: python python-3.x

这是代码:

text = input("What's your text:  ")
shift = int(input("What's your shift: "))

def caesar_shift(text, shift):
    cipher = ""
    for i in text:
        if i.isalpha():
            stayIn = ord(i) + shift
            if stayIn > ord('z'):
                stayIn -= 26
            lastLetter = chr(stayIn)
        cipher += lastLetter

        print("Your ciphertext is: ", cipher)

    return cipher

caesar_shift(text, shift)

当我运行它时,例如,测试是hello world,并且转换为1,我得到:

What's your text:  hello world
What's your shift: 1
Your ciphertext is:  i
Your ciphertext is:  if
Your ciphertext is:  ifm
Your ciphertext is:  ifmm
Your ciphertext is:  ifmmp
Your ciphertext is:  ifmmpp
Your ciphertext is:  ifmmppx
Your ciphertext is:  ifmmppxp
Your ciphertext is:  ifmmppxps
Your ciphertext is:  ifmmppxpsm
Your ciphertext is:  ifmmppxpsme

这是为什么?我做错了什么,提前谢谢!

2 个答案:

答案 0 :(得分:3)

你做

if i.isalpha():

但如果你没有其他条款。这意味着当它不是一个字母时,你也会添加最后一个字母。因此ifmmpp代替ifmmp而不是hello

该位应更改为:

if i.isalpha():
    stayIn = ord(i) + shift
    if stayIn > ord('z'):
        stayIn -= 26
    lastLetter = chr(stayIn)
    cipher += lastLetter
else:
    cipher += i

如果您不希望每个循环打印一次结果,请将其移出循环。

答案 1 :(得分:0)

要解决打印问题,您需要:

def caesar_shift(text, shift):
    cipher = ""
    for i in text:
        ...

        print("Your ciphertext is: ", cipher)

    return cipher

caesar_shift(text, shift)

但你应该

def caesar_shift(text, shift):
    cipher = ""
    for i in text:
        ...

    print("Your ciphertext is: ", cipher)

    return cipher

caesar_shift(text, shift)

或者更好

def caesar_shift(text, shift):
    cipher = ""
    for i in text:
        ...

    return cipher

print("Your ciphertext is: ", caesar_shift(text, shift))