Caesar Cipher encoding process (customizable input and shifting) in Python











up vote
3
down vote

favorite












So this code already works, but I would like to shorten it using list comprehension. Would it be better if it was in 1 line, or many? (I do know that readability is more important than short code, but I would like to master list comprehension, ternary operators, and conditional expressions).
Oh yes, if there is ANYTHING I can do to make my code better, more efficient, more readable and shorter, I would LOVE to know!



#Caesar Cipher, only lowercase and spaces    
listString = [x for x in input('What would you like to encode? ')]
change = int(input('How much would you like to shift? '))
change %= 26
def encode(listString,change):
encoded =
for c in listString:
if ord(c) + change > 122:
encoded.append(chr(ord(c) + (change - 26)))
continue
encoded = [" " if x == chr(32 + change) else x for x in encoded]
encoded.append(chr(ord(c) + change))
return "".join(encoded)

print(encode(listString,change))









share|improve this question




























    up vote
    3
    down vote

    favorite












    So this code already works, but I would like to shorten it using list comprehension. Would it be better if it was in 1 line, or many? (I do know that readability is more important than short code, but I would like to master list comprehension, ternary operators, and conditional expressions).
    Oh yes, if there is ANYTHING I can do to make my code better, more efficient, more readable and shorter, I would LOVE to know!



    #Caesar Cipher, only lowercase and spaces    
    listString = [x for x in input('What would you like to encode? ')]
    change = int(input('How much would you like to shift? '))
    change %= 26
    def encode(listString,change):
    encoded =
    for c in listString:
    if ord(c) + change > 122:
    encoded.append(chr(ord(c) + (change - 26)))
    continue
    encoded = [" " if x == chr(32 + change) else x for x in encoded]
    encoded.append(chr(ord(c) + change))
    return "".join(encoded)

    print(encode(listString,change))









    share|improve this question


























      up vote
      3
      down vote

      favorite









      up vote
      3
      down vote

      favorite











      So this code already works, but I would like to shorten it using list comprehension. Would it be better if it was in 1 line, or many? (I do know that readability is more important than short code, but I would like to master list comprehension, ternary operators, and conditional expressions).
      Oh yes, if there is ANYTHING I can do to make my code better, more efficient, more readable and shorter, I would LOVE to know!



      #Caesar Cipher, only lowercase and spaces    
      listString = [x for x in input('What would you like to encode? ')]
      change = int(input('How much would you like to shift? '))
      change %= 26
      def encode(listString,change):
      encoded =
      for c in listString:
      if ord(c) + change > 122:
      encoded.append(chr(ord(c) + (change - 26)))
      continue
      encoded = [" " if x == chr(32 + change) else x for x in encoded]
      encoded.append(chr(ord(c) + change))
      return "".join(encoded)

      print(encode(listString,change))









      share|improve this question















      So this code already works, but I would like to shorten it using list comprehension. Would it be better if it was in 1 line, or many? (I do know that readability is more important than short code, but I would like to master list comprehension, ternary operators, and conditional expressions).
      Oh yes, if there is ANYTHING I can do to make my code better, more efficient, more readable and shorter, I would LOVE to know!



      #Caesar Cipher, only lowercase and spaces    
      listString = [x for x in input('What would you like to encode? ')]
      change = int(input('How much would you like to shift? '))
      change %= 26
      def encode(listString,change):
      encoded =
      for c in listString:
      if ord(c) + change > 122:
      encoded.append(chr(ord(c) + (change - 26)))
      continue
      encoded = [" " if x == chr(32 + change) else x for x in encoded]
      encoded.append(chr(ord(c) + change))
      return "".join(encoded)

      print(encode(listString,change))






      python caesar-cipher






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 6 at 1:04









      200_success

      128k15149412




      128k15149412










      asked Dec 6 at 0:41









      Ascension

      163




      163






















          2 Answers
          2






          active

          oldest

          votes

















          up vote
          2
          down vote













          Some suggestions:




          • Pull out a function to shift a single character, and your top level code ends up being simply print(''.join([cipher(character) for character in input(…)]))

          • With an array containing the alphabet and a shifted array ("{}{}".format(alphabet[offset:], alphabet[:offset])) you can use str.translate to avoid any ord, chr, punctuation handling etc.

          • Use at least one linter like pycodestyle or flake8 to produce more idiomatic code.






          share|improve this answer




























            up vote
            1
            down vote













            A view more suggestions:




            • Put the function definition at the top


            • [x for x in input()] is the same as just input(). Strings are lists of characters!


            Combining my suggestings with the ones by @I0b0 you get something like the following:



            def encrypt(char, key):
            '''Encrypt lower and uppercase characters using the caesar cipher.'''
            if char.islower():
            return chr((ord(char) - ord('a') + key) % 26 + ord('a'))
            elif char.isupper():
            return chr((ord(char) - ord('A') + key) % 26 + ord('A'))
            return char

            message = input('What would you like to encode? ')
            key = int(input('How much would you like to shift? '))
            print(''.join([encrypt(c, key) for c in message]))





            share|improve this answer





















              Your Answer





              StackExchange.ifUsing("editor", function () {
              return StackExchange.using("mathjaxEditing", function () {
              StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
              StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
              });
              });
              }, "mathjax-editing");

              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "196"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              convertImagesToLinks: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f209118%2fcaesar-cipher-encoding-process-customizable-input-and-shifting-in-python%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              2
              down vote













              Some suggestions:




              • Pull out a function to shift a single character, and your top level code ends up being simply print(''.join([cipher(character) for character in input(…)]))

              • With an array containing the alphabet and a shifted array ("{}{}".format(alphabet[offset:], alphabet[:offset])) you can use str.translate to avoid any ord, chr, punctuation handling etc.

              • Use at least one linter like pycodestyle or flake8 to produce more idiomatic code.






              share|improve this answer

























                up vote
                2
                down vote













                Some suggestions:




                • Pull out a function to shift a single character, and your top level code ends up being simply print(''.join([cipher(character) for character in input(…)]))

                • With an array containing the alphabet and a shifted array ("{}{}".format(alphabet[offset:], alphabet[:offset])) you can use str.translate to avoid any ord, chr, punctuation handling etc.

                • Use at least one linter like pycodestyle or flake8 to produce more idiomatic code.






                share|improve this answer























                  up vote
                  2
                  down vote










                  up vote
                  2
                  down vote









                  Some suggestions:




                  • Pull out a function to shift a single character, and your top level code ends up being simply print(''.join([cipher(character) for character in input(…)]))

                  • With an array containing the alphabet and a shifted array ("{}{}".format(alphabet[offset:], alphabet[:offset])) you can use str.translate to avoid any ord, chr, punctuation handling etc.

                  • Use at least one linter like pycodestyle or flake8 to produce more idiomatic code.






                  share|improve this answer












                  Some suggestions:




                  • Pull out a function to shift a single character, and your top level code ends up being simply print(''.join([cipher(character) for character in input(…)]))

                  • With an array containing the alphabet and a shifted array ("{}{}".format(alphabet[offset:], alphabet[:offset])) you can use str.translate to avoid any ord, chr, punctuation handling etc.

                  • Use at least one linter like pycodestyle or flake8 to produce more idiomatic code.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Dec 6 at 0:57









                  l0b0

                  4,182923




                  4,182923
























                      up vote
                      1
                      down vote













                      A view more suggestions:




                      • Put the function definition at the top


                      • [x for x in input()] is the same as just input(). Strings are lists of characters!


                      Combining my suggestings with the ones by @I0b0 you get something like the following:



                      def encrypt(char, key):
                      '''Encrypt lower and uppercase characters using the caesar cipher.'''
                      if char.islower():
                      return chr((ord(char) - ord('a') + key) % 26 + ord('a'))
                      elif char.isupper():
                      return chr((ord(char) - ord('A') + key) % 26 + ord('A'))
                      return char

                      message = input('What would you like to encode? ')
                      key = int(input('How much would you like to shift? '))
                      print(''.join([encrypt(c, key) for c in message]))





                      share|improve this answer

























                        up vote
                        1
                        down vote













                        A view more suggestions:




                        • Put the function definition at the top


                        • [x for x in input()] is the same as just input(). Strings are lists of characters!


                        Combining my suggestings with the ones by @I0b0 you get something like the following:



                        def encrypt(char, key):
                        '''Encrypt lower and uppercase characters using the caesar cipher.'''
                        if char.islower():
                        return chr((ord(char) - ord('a') + key) % 26 + ord('a'))
                        elif char.isupper():
                        return chr((ord(char) - ord('A') + key) % 26 + ord('A'))
                        return char

                        message = input('What would you like to encode? ')
                        key = int(input('How much would you like to shift? '))
                        print(''.join([encrypt(c, key) for c in message]))





                        share|improve this answer























                          up vote
                          1
                          down vote










                          up vote
                          1
                          down vote









                          A view more suggestions:




                          • Put the function definition at the top


                          • [x for x in input()] is the same as just input(). Strings are lists of characters!


                          Combining my suggestings with the ones by @I0b0 you get something like the following:



                          def encrypt(char, key):
                          '''Encrypt lower and uppercase characters using the caesar cipher.'''
                          if char.islower():
                          return chr((ord(char) - ord('a') + key) % 26 + ord('a'))
                          elif char.isupper():
                          return chr((ord(char) - ord('A') + key) % 26 + ord('A'))
                          return char

                          message = input('What would you like to encode? ')
                          key = int(input('How much would you like to shift? '))
                          print(''.join([encrypt(c, key) for c in message]))





                          share|improve this answer












                          A view more suggestions:




                          • Put the function definition at the top


                          • [x for x in input()] is the same as just input(). Strings are lists of characters!


                          Combining my suggestings with the ones by @I0b0 you get something like the following:



                          def encrypt(char, key):
                          '''Encrypt lower and uppercase characters using the caesar cipher.'''
                          if char.islower():
                          return chr((ord(char) - ord('a') + key) % 26 + ord('a'))
                          elif char.isupper():
                          return chr((ord(char) - ord('A') + key) % 26 + ord('A'))
                          return char

                          message = input('What would you like to encode? ')
                          key = int(input('How much would you like to shift? '))
                          print(''.join([encrypt(c, key) for c in message]))






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Dec 6 at 5:15









                          Noah Haasis

                          1112




                          1112






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Code Review Stack Exchange!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              Use MathJax to format equations. MathJax reference.


                              To learn more, see our tips on writing great answers.





                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                              Please pay close attention to the following guidance:


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f209118%2fcaesar-cipher-encoding-process-customizable-input-and-shifting-in-python%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Terni

                              A new problem with tex4ht and tikz

                              Sun Ra