2013-07-24 331 views
1
def caesar(plaintext,shift): 
    alphabet=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] 

    #Create our substitution dictionary 
    dic={} 
    for i in range(0,len(alphabet)): 
     dic[alphabet[i]]=alphabet[(i+shift)%len(alphabet)] 

    #Convert each letter of plaintext to the corrsponding 
    #encrypted letter in our dictionary creating the cryptext 
    ciphertext=("") 
    for l in plaintext.lower(): 
      if l in dic: 
       l=dic[l] 
       ciphertext+=l 
      return ciphertext 

#Example useage 
plaintext="the cat sat on the mat" 
print "Plaintext:", plaintext 
print "Cipertext:", (caesar(plaintext,29)) 

cipertext只打印一个字母,而不是在caesar shift中打印'明文'变量。我希望它能打印整个句子。Python - 为什么这个循环只打印1个字母?

感谢

回答

8

这是因为你的return ciphertext缩进错误。你从for循环的第一次迭代返回。 (缩进在Python中很重要!)

for l in plaintext.lower(): 
      if l in dic: 
       l=dic[l] 
       ciphertext+=l 
      return ciphertext # Indented to match level of `if`. 

修复它。

for l in plaintext.lower(): 
     if l in dic: 
      l=dic[l] 
      ciphertext+=l 
    return ciphertext 

夫妇指针

  1. 而是在你的代码清单中的所有字母的,你可以设置alphabets = string.ascii_lowercase
  2. 你不需要一个变量来存储dic[l],只是做ciphertext += dic[l]
+0

感谢我现在的工作。但还有一个问题。凯撒没有空格,它只是一串字母,就像这样:wkhdwvdwrqwkhpdw – BubbleMonster

+0

这是因为它不符合'if if in dic'的标准,所以你需要为这样的情况制作一个'else'声明,无论如何。 (我不认为你在轮班中改变了标点符号)。 –

2

你需要修复的缩进了return语句:

for l in plaintext.lower(): 
    if l in dic: 
     l=dic[l] 
     ciphertext+=l 
    # <-- if you return here, then you will loop only once.  
return ciphertext 
3

与string.translate做的更好:)

import string 
def caesar(plaintext,shift): 
    alphabet=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] 
    alphabet_shifted = alphabet[shift:]+alphabet[:shift] 
    tab = string.maketrans("".join(alphabet),"".join(alphabet_shifted)) 
    return plaintext.translate(tab) 
+1

+1,这太棒了!将字母表作为'string.ascii_lowercase',那么你不需要'“”.join(...)'。 –

+0

是的我同意,但这种方式可以与你想要定义的任何字母表一起工作......作为列表或元组 –