Program 5: Caesar Cipher This problem builds on the Caesar Cipher program from a
ID: 3585541 • Letter: P
Question
Program 5: Caesar Cipher This problem builds on the Caesar Cipher program from a previous lab. If you didn’t get to that part of the lab, here’s some code that starts with a word, “Minneapolis” and shifts each letter by 6 letters to produce a coded word. word = "Minneapolis" shift = 6 coded_word = "" for letter in word: coded_letter = chr(ord(letter) + shift) coded_word = coded_word + coded_letter print(word + " in code is " + coded_word) Please write a function that takes a string (a word) and a number (the number of letters to shift) as arguments. The function should shift each letter by the number given; and return the coded word. Or, your function can take a sentence and a number as an argument, and return a coded sentence. Now, can you write a decoding function? This function will take a coded string and a number as arguments. Final version: write an encrypting/decrypting program. Ask the user if they want to encrypt or decrypt, and call the appropriate function. What if the user has lots of strings to encrypt and decrypt? Perhaps you could use a while true loop so the program repeats until the user wants to quit? Using python.
Explanation / Answer
def encrypt(str, n): i = 0 l = len(str) encoded_str = '0' while True: if( i == l): break if ord(str[i]) >= 97 and ord(str[i]) 122: diff = 122 - ord(str[i]) en = 96 + (n-diff) encoded_str = encoded_str + chr(en) else: en = ord(str[i]) + n encoded_str = encoded_str + chr(en) if ord(str[i]) >= 65 and ord(str[i]) 90: diff = 90 - ord(str[i]) en = 64 + (n-diff) encoded_str = encoded_str + chr(en) else: en = ord(str[i]) + n encoded_str = encoded_str + chr(en) if ord(str[i]) == 32: encoded_str = encoded_str + '_' i += 1 print (" Encrypted String is:-") print encoded_str[1:] def decrypt(str, n): i = 0 l = len(str) decoded_str = '0' while True: if (i == l): break if ord(str[i]) >= 97 and ord(str[i]) = 65 and ord(str[i]) 3: print ("Invalid choice...") if ch == 1: str = raw_input("Enter your string...") num = input("Enter number of shift for each letter to encrypt...") encrypt(str, num) if ch == 2: str = raw_input("Enter your string...") num = input("Enter number of shift for each letter to decrypt...") decrypt(str, num) if ch == 3: break #space in string is resulted as "_"(underscore).Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.