简体   繁体   English

Python-为什么此for循环仅打印1个字母?

[英]Python - why does this for loop only print 1 letter?

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

The cipertext prints just one letter, instead of printing the 'plaintext' variable in caesar shift. 密文只打印一个字母,而不是在凯撒移位中打印'plaintext'变量。 I want it to print the whole sentence. 我要它打印整个句子。

Thanks 谢谢

This is because your return ciphertext is indented wrong. 这是因为您的return ciphertext缩进了错误。 You return from the first iteration of the for loop. 您将从for循环的第一次迭代中返回。 (Indentation matters a lot in Python!) (缩进在Python中非常重要!)

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

Fix it to. 修复它。

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

Couple of Pointers 几个指针

  1. Instead of listing out all alphabets in your code, you can just set alphabets = string.ascii_lowercase . 除了列出代码中的所有字母外,您还可以设置alphabets = string.ascii_lowercase
  2. You don't need a variable to store dic[l] , just do ciphertext += dic[l] . 您不需要变量来存储dic[l] ,只需做ciphertext += dic[l]

do it better with string.translate :) 用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)

You need to fix the indents for the return statement: 您需要修复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  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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