【问题标题】:Why is this python code printing one letter at a time?为什么这个 python 代码一次打印一个字母?
【发布时间】:2021-05-28 08:39:12
【问题描述】:
def encrypt():
    msg = input("Enter the message you would like to encrypt: ").strip()
    print()
    key = int(input("Enter key to encrypt, a number 0-25: "))

    encryptedMessage = ""
    for ch in msg:
        if ord(ch) == 32: 
            encryptedMessage += ch 
            
        elif ord(ch) + key > 122:
            #after z moves back to a, a = 97, z = 122
            temp = (ord(ch) + key) - 122 
            encryptedMessage += chr(96+temp)
             
        elif (ord(ch) + key > 90) and (ord(ch) < 96):
            #moving back to a after z
            temp = (ord(ch) + key) - 90
            encryptedMessage += chr(64+temp)
                                          
        else:
            #incase of letters being both caps
            encryptedMessage += chr(ord(ch) + key)
       
        print(encryptedMessage)

        main()

抱歉,我真的不知道是什么导致了这种情况发生的大量代码。这应该是一个 Caesar Cipher 加密程序,您输入消息并移位,它应该打印代码。但是,它只打印一个字母,如果我在最后删除 main(),它会一次打印每个字母,例如,让我们说这个词是 Lemons it go、L、LE、LEM 等等。如果有人知道如何帮助解决这个问题,我将不胜感激,谢谢!

【问题讨论】:

  • 您的 print 在您的 for 循环内。

标签: python encryption caesar-cipher


【解决方案1】:

只是取消缩进 print(encryptedMessage) 所以它不在循环中。

def encrypt():
    ...
    for ch in msg:
        ...
    print(encryptedMessage)

【讨论】:

    【解决方案2】:

    这里,这应该适合你的需要

    def encrypt():
        msg = input("Enter the message you would like to encrypt: ").strip()
        print()
        key = int(input("Enter key to encrypt, a number 0-25: "))
    
        encryptedMessage = ""
        for ch in msg:
            if ord(ch) == 32:
                encryptedMessage += ch
    
            elif ord(ch) + key > 122:
                #after z moves back to a, a = 97, z = 122
                temp = (ord(ch) + key) - 122
                encryptedMessage += chr(96+temp)
    
            elif (ord(ch) + key > 90) and (ord(ch) < 96):
                #moving back to a after z
                temp = (ord(ch) + key) - 90
                encryptedMessage += chr(64+temp)
    
            else:
                #incase of letters being both caps
                encryptedMessage += chr(ord(ch) + key)
    
        print(encryptedMessage)
    
    encrypt()
    

    现在,如果您看到,它可以完美运行

    Enter the message you would like to encrypt: Hello World
    
    Enter key to encrypt, a number 0-25: 15
    Wtaad Ldgas
    
    Process finished with exit code 0
    

    【讨论】:

    • 没问题,顺便说一句,你是怎么解密的
    • 其实我想通了,再加密25次就可以解加密
    猜你喜欢
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    相关资源
    最近更新 更多