0

これはコードです:

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

どうしてこれなの?私は何か間違ったことをしていますか、事前に感謝します!

4

2 に答える 2

3

あなたがやる

if i.isalpha():

しかし、if の else 句はありません。つまり、文字でない場合でも最後の文字を追加します。したがって、 forifmmppの代わりに.ifmmphello

そのビットを次のように変更する必要があります。

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

ループごとに結果を出力したくない場合は、ループの外に移動します。

于 2013-08-16T07:17:52.227 に答える
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)) 
于 2013-08-16T08:11:35.590 に答える