简体   繁体   中英

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:

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 .

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)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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