Python - 为什么这个for循环只打印1个字母?

时间:2013-07-24 18:23:15

标签: python

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中打印'plaintext'变量。我想要打印整个句子。

由于

3 个答案:

答案 0 :(得分: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. ,而不是列出代码中的所有字母
  3. 您不需要变量来存储dic[l],只需要ciphertext += dic[l]

答案 1 :(得分: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)

答案 2 :(得分: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