Advertisement
Guest User

Untitled

a guest
Jul 25th, 2017
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.24 KB | None | 0 0
  1. import cs50
  2. import sys
  3.  
  4. def main():
  5.     # make sure the user gives the right parameters
  6.     if len(sys.argv) != 2:
  7.         print("python caesar.py key")
  8.         exit(1)
  9.        
  10.     # make sure the input are valid alabetical characters
  11.     if sys.argv[1].isalpha() == False:
  12.         print("plase provide valid input")
  13.         exit(2)
  14.     else:
  15.         key = sys.argv[1]
  16.    
  17.     # prompt the user for text to be ciphered
  18.     print("plaintext: ", end="")
  19.     plaintext = cs50.get_string()
  20.     print("ciphertext: ", end="")
  21.    
  22.     # prepare to do the ciphering
  23.     key_index = 0
  24.     key_len = len(sys.argv[1])
  25.     ciphertext = []
  26.    
  27.     # loop and cipher
  28.     for i in plaintext:
  29.         if i.isalpha():
  30.             cipher_key = ord(key[key_index % key_len].lower()) - 97
  31.             ciphertext.append(cipher_this(i, cipher_key))
  32.             cipher_key += 1
  33.         else:
  34.             ciphertext.append(i)
  35.            
  36.     # print the final solution
  37.     print("".join(ciphertext))
  38.    
  39.     exit(0)
  40.    
  41. def cipher_this(char, key):
  42.     if char.isupper():
  43.         return chr(((ord(char) - 65 + key) % 26) + 65)
  44.     elif char.islower():
  45.         return chr(((ord(char) - 97 + key) % 26) + 97)
  46.  
  47. if __name__=="__main__":
  48.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement