[英]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 几个指针
alphabets = string.ascii_lowercase
. alphabets = string.ascii_lowercase
。 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.