2013-08-16 52 views
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 

這是爲什麼?我做錯了什麼,提前致謝!

回答

3

你做

if i.isalpha(): 

,但你有,如果沒有else子句。這意味着,如果它不是一個字母,也可以添加最後一個字母。因此,ifmmpp而不是ifmmphello

該位應改爲:

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

如果你不想成爲每一次循環打印出來的結果,將其移動外循環。

+0

沒有答案是正確的,我想知道爲什麼它會像這樣打印出來,我如何得到最後一個答案? – Samir

+0

@ Samir:不,答案是不正確的,如果你將它移回來,你會注意到。我更新瞭解釋以涵蓋您的其他問題。 –

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