Caesar Cipher issue - python

I am trying to implement a Caesar cipher.
I have tried to return message in the function, but I get an error message (outside function). Can anyone help, please?
Thanks in advance
cat
cate
catec
catecv
message = input("type message ")
shift = int(input("Enter number to code "))
message = message.lower() #convets to lower case
print (message)
for a in message:
if a in "abcdefghijklmnopqrstuvwxyz":
number = ord(a)
number += shift
if number > ord("z"):
number -= 26
elif number < ord("a"):
number += 26
message = message + (chr ( number))
print (message)

Here's Python 3 Caesar cipher implementation that uses str.translate():
#!/usr/bin/env python3
import string
def caesar(plaintext, shift, alphabet=string.ascii_lowercase):
shifted_alphabet = alphabet[shift:] + alphabet[:shift]
return plaintext.translate(plaintext.maketrans(alphabet, shifted_alphabet))
message = input("type message to encode")
shift = int(input("Enter number to code "))
print(caesar(message.lower(), shift))
Here's Python 2 version of Caesar Cipher.

Related

Python Caesar cipher code flaws

I'm new to Python. This is my 3rd project and I'm facing to some obstacles. Here I have a Caesar cipher project. It seems to do everything I needed it to do that accepts only capital letters, no special characters, no lower case letters, no spaces.
However, I have two issues:
It MUST only accept numbers that range from 1 to 26. Unfortunately, it's also accepting numbers that are even higher than 26.
Regardless of a key size it only shifts letters by 1 digit. Ideally, it must shift the letters according to entered key size:
this is where problem(s) occurring
It would be tremendous help if anyone could provide a solution or give suggestions to fix above issues. Thank you so much for your time and attention!
Here is my code:
MAX_NUMBER_KEY = 26
def getMode():
while True:
print('Please make your selection from the following "E" for encryption or "D" for decryption:')
mode = raw_input()
if mode in 'E D'.split():
return mode
else:
print('Error! Please try again and make sure to choose only "E" or "D"!')
def getText():
while True:
print('Enter your text that you would like to encrypt or decrypt:')
text = raw_input()
if text.isalpha() and text.isupper():
return text
else:
print('Error! No spaces, no special characters or numbers! Please only use letters!')
def getKey():
key = 0
while True:
print('Enter your number key for "K" (1-%s)' % (MAX_NUMBER_KEY))
key = int(raw_input().isdigit())
if (key >= 1 and key <= MAX_NUMBER_KEY):
return key
else:
print('Error! Please try again and choose only numbers between (1-26)!')
def getEncryptedMessage(mode, text, key):
if mode[0] == 'D':
key = -key
encrypted = ''
for each in text:
if each.isalpha():
num = ord(each)
num += key
if each.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A'):
num += 26
encrypted += chr(num)
else:
encrypted += each
return encrypted
mode = getMode()
message = getText()
key = getKey()
print('Your encrypted message is:')
print(getEncryptedMessage(mode, message, key))
In getKey(), raw_input().isdigit() returns a boolean, so by casting it to an int, you are going to be doing int(True) or int(False) which is 1 and 0 respectively.

How to run loop until I get each individual letter

I am working on my Caesar Cipher program and I am running into an issue when I am trying to encrypt my message. The error is 'function is not iterable'. So basically I want to run the for loop until it runs through all the letters in the string.
def message():
message = input("Enter your message here: ").upper()
return message
def key():
while True:
key = int(input("Enter your shift or key between the numbers of 1-26: "))
if key >=1 and key<=26:
return key
def encrypt(message, key):
output = []
for symb in message:
numbers = ord(symb) + 90 - key
output.append(numbers)
print(output)
Don't reuse names. Rename the message and key arguments of encrypt to something else.
def encrypt(m, k):
...
def main():
encrypt(message(), key())
You have variables with the same name as your functions and this is causing a conflict when it runs.
Make it clearer which is which.
def message():
msg = input("Enter your message here: ").upper()
return msg
def key():
while True:
k = int(input("Enter your shift or key between the numbers of 1-26: "))
if k >=1 and k <=26:
return k
etc.

My program runs but it doesn't output an Encrypted Message

The code I wrote is a Vignere Cipher encryption program that uses a keyword to encrypt a message. I wrote this code and when I finished it I ran it and it did all it was supposed to but output the encrypted message. See my code below, any help is gratefully received:
ans = False
print(""" *****Hello. Welcome to the Vignère Cipher Encryption Program*****
***This program uses a keyword that is repeated until it
matches the same lenght of the message and then adds its
numerical value to the numerical value of the message and
outputs the encrypted message in alpha.
Please press:
E to Encrypt
D to Decrypt
or double tap enter to quit.
""")
ans=input("What would you like to do now???")
if ans == "E":
plaintext = input("Please enter a message to be encrypted: ").upper()
keyword = input("Please enter a keyword to be used to encrypt a message (alpha only): ").upper()
ciphered = " "
for i in range (len(plaintext)):
char = plaintext[i]
alphakeywordvalue = ord(keyword[i%len(keyword)]) - ord("A")+1
if char.isupper():
if ans == "E" :
value = ord(char) + alphakeywordvalue
if value > ord("Z"):
value -= 26
print ("Your encrypted text is:", ciphered)
elif ans == "D":
plaintext = input("Please enter a message to be dencrypted: ").upper()
keyword = input("Please enter a keyword to be used to dencrypt a message (alpha only(make sure that it is the same keyword used to encrypt the message)): ").upper()
ciphered = " "
for i in range (len(plaintext)):
char = plaintext[i]
alphakeywordvalue = ord(keyword[i%len(keyword)]) - ord("A")+1
if char.isupper():
if ans == "D" :
value = ord(char) - alphakeywordvalue
if value <ord("A"):
value += 26
ciphered += chr(value)
print ("Your decrypted text is:", ciphered)
This is not a good style of writing code. Very shabby and hard to read. You should make methods for individual parts and create a separate main() like section to interact with the user, if required. Engine should be hidden, car body should be polished. Keep them separate. And yes, DO NOT REPEAT YOURSELF
Well, here's my re-written code. Important parts contain the comments. Errors are explained after it..
def encrypt(message, key, direction='E'):
# Look here. There are three arguments. Third one takes 'E' to encrypt
# and anything else to decrypt. You can modify to handle more cases
ciphered = "" # Initialize. You did it almost well
for i in range (len(message)):
char = message[i]
alphakeywordvalue = ord(key[i%len(key)]) - ord("A")+1 # Perfect. We took the key
if direction=='E': # To encrypt
value = ord(char) + alphakeywordvalue
else: # To decrypt
value = ord(char) - alphakeywordvalue
ciphered += chr(value) # chr is the inverse of ord. It gets the character back
# You missed this line
return ciphered
That's it. Now you can write the code to interact with user or other modules. Here's a sample test:-
message = "Hello World"
key = "abc"
print "ORIGINAL : "+message
encoded_message = encrypt(message, key, 'E')
print "ENCRYPTED : "+encoded_message
plain_message = encrypt(encoded_message, key, 'D')
print "DECRYPTED : "+plain_message
Here's the output:
Now you can edit this method to handle more cases like out of ascii range characters etc.
How could it print the encrypted message, the encryption routine never changes ciphered from an empty string.
if ans == "E":
plaintext = input("Please enter a message to be encrypted: ").upper()
keyword = input("Please enter a keyword to be used to encrypt a message (alpha only): ").upper()
1)-> ciphered = " "
for i in range (len(plaintext)):
char = plaintext[i]
alphakeywordvalue = ord(keyword[i%len(keyword)]) - ord("A")+1
2)-> if char.isupper():
3)-> if ans == "E" :
value = ord(char) + alphakeywordvalue
if value > ord("Z"):
value -= 26
4)-> print ("Your encrypted text is:", ciphered)
ciphered set to empty string, is never changed.
You always know char is upper, because you made all the plaintext upper()
You know ans == "E" because you tested it earlier
This print() is so far indented it tries to print every time through the loop

Caesar Cipher decode not working

I am trying to get the Caesar cipher working, I can get the encode, but not the decode without using -shift. I think it might be while True, tied with little success
Thanks all in advance
def helper(message, shift):
message = message.lower()
secret = ""
for c in message:
if c in "abcdefghijklmnopqrstuvwxyz":
num = ord(c)
num += shift
if num > ord("z"): # wrap if necessary
num -= 26
elif num < ord("a"):
num += 26
secret = secret + chr(num)
else:
# don't modify any non-letters in the message; just add them as-is
secret = secret + c
return secret
# Encrypts the given string using a Caesar cipher and returns the result.
def encrypt(message):
return helper(message, x)
# Decrypts a string that was previously encrypted using a Caesar cipher and returns the result.
def decrypt(message):
return helper(message, x)
t=input('e or d ')
msg = input("Your message to encode? ")
x = int(input('no '))
if len (msg) > 0:
# wants to encrypt
secret = encrypt(msg)
print("The encoded message is:", secret)
else:
# empty message; wants to decrypt
secret = input("Your message to decode? ")
if len(secret) > 0:
msg = decrypt(secret)
print("The decoded message is:" ,msg)
Decryption should shift in the opposite direction of encryption.
def decrypt(message):
return helper(message, -x)
Now you can decrypt and encrypt with the same cipher number.
x = 5
msg = "hello"
print("plaintext message:", msg)
print("encrypted message:", encrypt(msg))
print("decrypted message:", decrypt(encrypt(msg)))
Result:
plaintext message: hello
encrypted message: mjqqt
decrypted message: hello

Python Vigenere Code repeating error

We have to do a vigenere cipher for a project, and my code just keeps repeating itself. Like it wont run the encrypt or decrypt.
here is my code.
like this is what it does for an example..
"Hey There user!
whats your message??hi
How many letters are in the message?2
Do you want to decrypt or encrypt?decrypt
Lets decrypt your message!!
Do you want to decrypt or encrypt?"
print "Hey There user!"
def vig():
dore = raw_input("Do you want to decrypt or encrypt?")
if "decrypt" in dore:
print "Lets decrypt your message!!"
else:
print "lets encrypt your message!!"
def dore(message):
encrypt = ''
decrypt = ''
if "encrypt" in vig():
for i in range(0, len(message)):
e = ord(message[i]) + ord(key[i%len(key)]) - 65
if e > 90:
e -= 26
encrypt += chr(e)
print encrypt
if "decrypt" in vig():
e = ord(message[i]) - ord(key[i%len(key)]) + 65
if e < 65:
e += 26
decrypt += chr(e)
print decrypt
####################################
###########################################:)#####
message = raw_input("whats your message??")
key = raw_input("How many letters are in the message?")
vig()
dore(message)
message = message
encrypt = ''
decrypt = ''
One of the first things you do in dore is call vig again:
if "encrypt" in vig():
Try separating encryption and decryption into two functions and calling them accordingly:
def vig(message):
ui = raw_input("Encrypt or decrypt? ").lower()
if "decrypt" in ui:
return decrypt(message)
else:
return encrypt(message)
Also, the user doesn't need to enter the length of the message, just do:
key = len(message)

Categories

Resources