简体   繁体   English

为什么我的ca撒轮班不能正常工作?

[英]Why won't my caesar shift work properly?

This is the code: 这是代码:

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)

When I run it, and for example, the test is hello world, and the shift is 1, I get: 当我运行它时,例如,测试是“ 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

Why is this? 为什么是这样? Am I doing something wrong, thanks in advance! 我做错什么了吗,谢谢!

You do 你做

if i.isalpha():

but you have no else-clause for that if. 但如果没有,您别无他法。 That means that you add the last letter also when it is not a letter. 这意味着您在最后一个字母不是字母时也要添加它。 Hence ifmmpp instead of ifmmp for hello . 因此,用ifmmpp代替ifmmp hello

That bit should be changed to: 该位应更改为:

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

If you don't want the result to be printed out once for every loop, move it outside the loop. 如果您不希望每个循环将结果打印一次,请将其移出循环。

To fix the print problem, you have: 要解决打印问题,您可以:

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

        print("Your ciphertext is: ", cipher)

    return cipher

caesar_shift(text, shift)

But you should have 但是你应该有

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

    print("Your ciphertext is: ", cipher)

    return cipher

caesar_shift(text, shift)

Or better yet 还是更好

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

    return cipher

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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