Elaboration of cipher in python

Asked

Viewed 1,055 times

3

Hey, guys, I’m new here and in the programming world, so any criticism is welcome. I have a problem with this cesar cipher I’ve been trying to do. They could point out possible errors, and ways to improve this code by adding functions.

   print ("-=-=-=-=-=-=-=-=-=-=-=-=-=-")
print("Criptografia de César")
print(" ")

#recebe a chave de critografia e valida
chave = int(input("digite a chave de criptografia (ate 26)\n"))
while chave > 26 or chave < 0:  
    print(" ")
    chave = input("chave inválida, tente novamente")

base = 'abcdefghijklmnopqrstuvwxyz'

#escolhe o modo
modo = str(input("Deseja encriptar ou descriptar\n"))

#insere e formata o texto
text= str(input("Digite o texto a ser criptografado\n"))
tamanho_txt = len(text)
text = text.lower()


#insere o texto final
cripto =''

char = 0
    #escolhe o modo
if (modo == 'e' or modo == 'encriptar') :

    while char <= tamanho_txt:

            #recebe o word de comparação
        word = text[char]

            #enquanto o word estiver coontido na base de comparação
        for word in base[0:len(base)]:

                #encontra o numero da posição dp word na base
            posicion = base.find(word)

                #soma a chave á posição
            posicion + chave

                # se a posição for maior que a base ira calcular a diferença
            if(posicion > len(base)):
                posicion = posicion - len(base)

        #concatena a o word encontrado           
        cripto = cripto + base[posicion]

        char = char +1

if (modo == 'd' or modo == 'decriptar'):
        # contador do texto
    while char <= tamanho_txt:
            # recebe o word da posição
        word = text[char]
            #condição se o word estiver contido na base
        for word in base[0:len(base)]:
                #encontra a posição
            posicion = base.find(word)
                #subtrai a chave
            posicion - chave
                #condicional se a posição foi menor que 0
            if posicion <= 0:
                    # subtrai o valor absoluto da base para encontrar a posição
                posicion = len(base)- abs(posicion)

        #resultado            
        cripto = cripto + base[posicion]
        char = char + 1      

print("sua mensagem \n" + cripto)

2 answers

4


Hello. Well, your code is pretty messed up. Also, it has many irregularities that cannot happen or that are extremely redundant.
I can name the two I saw when I read your code:

  • Two Ifs for same data:

When we are treating two or more possibilities for a certain given (in this case here is the user input), the ideal is for a if/elif/else. If you want to know more about the cause, we have already a question and answer in Sopt.
Then we can already replace the second if by a elif.

  • For loop with strange construction

The for loop traverses all items of an iterable object (strings, tuples, sets, dictionaries and lists), and in its case there is no need to traverse using the [0:len(base)], since this is exactly the same thing as by itself base as an argument from for.

I mean, we just rename for word in base[0:len(base)]: for for word in base.

  • There’s a line that does nothing.

When you do any operation, Python just performs. The result you only save to memory if you assign to a variable, or add to some object that looks like an array (like an dict or a list). The line in question is

posicion + chave

, where the correct would be

posicion += chave

For the rest, I believe that the error is really logical. In this case, could you explain your algorithm? I really couldn’t quite understand what his intention was by typing what was typed. But on logic, I can point out some errors:

  • It seems to me that you don’t quite understand the concept of tie for. He does not check the condition, he does what I just said: iterates each item of an eternal object, in the case of string, each item is a character. And instead of using the groundwork, you should use the user input text.
  • The noose while in this case it is also useless, since the limitation of the input size can already be imposed on a for loop, which traverses exactly all characters of the data that the user entered (input).
  • In addition, the two ifs in case of "overload" (when the letter is z and I have to go to to, or vice versa) you just applied an incorrect logic. The correct one would be respectively, if(posicion > len(base)): and if posicion < 0:. Where the first must indicate if it is only greater than the length of the alphabet and the second only if it is less than 0.

Correcting all errors, we come to the final code:

print ("-=-=-=-=-=-=-=-=-=-=-=-=-=-")
print("Criptografia de César")
print(" ")

#recebe a chave de critografia e valida
chave = int(input("digite a chave de criptografia (ate 26)\n"))
while chave > 26 or chave < 0:  
    print(" ")
    chave = input("chave inválida, tente novamente")

base = 'abcdefghijklmnopqrstuvwxyz'

#escolhe o modo
modo = str(input("Deseja encriptar ou descriptar\n"))

#insere e formata o texto
text= input("Digite o texto a ser criptografado\n")
text = text.lower()


#insere o texto final
cripto =''

    #escolhe o modo
if (modo == 'e' or modo == 'encriptar') :
    for word in text:
                #encontra o numero da posição dp word na base
        posicion = base.find(word)

            #soma a chave á posição
        posicion += chave

            # se a posição for maior que a base ira calcular a diferença
        if(posicion > len(base)):
            posicion = posicion - len(base)

    #concatena a o word encontrado           
        cripto = cripto + base[posicion]

elif (modo == 'd' or modo == 'decriptar'):
        # contador do texto
            # recebe o word da posição
            #condição se o word estiver contido na base
    for word in text:
            #encontra a posição
        posicion = base.find(word)
            #subtrai a chave
        posicion -= chave
            #condicional se a posição foi menor que 0
        if posicion < 0:
                # subtrai o valor absoluto da base para encontrar a posição
            posicion = len(base)- abs(posicion)

    #resultado            
        cripto = cripto + base[posicion]

print("sua mensagem \n" + cripto)
  • 1

    +1 well completed answer

  • 1

    too cool guy, thanks for the tips and promise to work to improve my flaws, you addressed all the doubts I had. As you can see I’m still learning the basics, I made this code only as a self-challenge, and I’ve realized that the "think" that is right and the "right" are very different. Thank you.

1

Python has a perfect function for the César cipher, which is the str.translate:

def cesar(texto, deslocamento):
    alfabeto = string.ascii_lowercase
    alfabeto_deslocado = alfabeto[deslocamento:] + alfabeto[:deslocamento]
    tabela = string.maketrans(alfabeto, alfabeto_deslocado)
    return texto.translate(tabela)

For example:

>>> print(cesar('ola', 10))
yvk

to decrypt just reverse the displacement signal:

>>> print(cesar('yvk', -10))
ola

Browser other questions tagged

You are not signed in. Login or sign up in order to post.