How to run loop until I get each individual letter - python

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.

Related

Need Guidance with some Python code (Substitute Cypher Python)

I have some code already but I got feedback on how to pass the rest of the criteria but I have no idea how to do it.
Assignment brief:
You are working in a Newspaper office that handles the reports from their journalists. You have been asked to design a program that will be used to help them send confidential reports in that others cannot read as email is not secure, we need to generate an encryption key that they can encode their scoops and documents when sent by email.
The program will need to generate the key. Encode the message, export the key, import a key from another person and decode a message. It will be a simple substitution cipher. The key needs to be made up out of all Alphanumeric Characters and some Special Characters. It will be a single key per session so you will need to save the key if you close the program otherwise you won’t be able to decode those messages used to encode them.
All projects start with planning it is the most important part that can make or break a project so ensure this is carried out correctly
Pass, Merit and Distinction Requirements
What the feedback says to do:
You were asked to import a key and export a key your program doesn't allow this so you would need to resubmit to get Pass4 and Pass6
Code I have done so far below
def run():
x=input("code or decode? ")
if x == "code":
a=list("")
import string
alpha = str("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
message=input("What is your message to encode? ")
x=len(message)
y=0
z=0
for counter in range(x):
y=y+1
letter = alpha.find(message[z:y])
z=z+1
letter=letter+13
if letter > 24:
letter=letter-24
letter=alpha[letter:letter+1]
if counter != x-1:
print(letter,end="")
else:
print(letter)
x=input("type yes to go again? ")
if x == "yes":
run()
else:
input()
else:
a=list("")
import string
alpha = str("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
message=input("What is your message to decode? ")
x=len(message)
y=0
z=0
for counter in range(x):
y=y+1
letter = alpha.find(message[z:y])
z=z+1
letter=letter-13
if letter < 0:
letter=24+letter
letter=alpha[letter:letter+1]
if counter != x-1:
print(letter,end="")
else:
print(letter)
x=input("again? ")
if x == "yes":
run()
else:
input()
run()
I did some research and come up with this.
You can use it as it is or edit it to meet your needs. Hope it helps.
Update.1: The longer the message, the bigger the encryption key will be. One solution for this is to use zlib.compress method in order to shrink the key, and then decompress it when needed.
Update.2: Added the export/import functionality of the encryption key using a Json file (you can of course choose other way of storing data) along with a title assigned to it, so you have the choice to either enter the title or enter the encryption key of the message for decryption. The title is just optional and for simplicity purposes, you can get rid of it if you want to. You'll also notice the code contains lots of if/else statements, that's just so you know where you currently are and what choices you have.
A GUI based would be better.
import string
import json
import os
# A list containing all characters
alpha = string.ascii_letters
def code(title, message, key = 6):
temp_dict = {}
cipher=[]
for i in range(len(alpha)):
temp_dict[alpha [i]] = alpha [(i+key)%len(alpha )]
# Generating the encryption key
for char in message:
if char in alpha :
temp = temp_dict[char]
cipher.append(temp)
else:
temp =char
cipher.append(temp)
# This code is needed to decode the expected message so make sure to save it by any method you want,
# otherwhise it'll generate a random text.
cipher= "".join(cipher)
main_data = {title : cipher}
file_name = "encryption_key.json"
if os.path.exists(file_name):
with open(file_name, "r+") as file:
data = json.load(file)
data[0].update(main_data)
file.seek(0)
json.dump(data, file)
else:
with open(file_name, "w") as file:
json.dump([main_data], file)
print("Encryption code :",cipher)
def decode(cipher, key = 6):
temp_dict = {}
for i in range(len(alpha)):
temp_dict[alpha [i]] = alpha [(i-key)%(len(alpha ))]
# Decoding the message
decoded_text = []
for char in cipher:
if char in alpha :
temp = temp_dict[char]
decoded_text.append(temp)
else:
temp = char
decoded_text.append(temp)
decoded_text = "".join(decoded_text)
return decoded_text
while True:
# There is an optional parameter (key) within the function which you can change according to your preference.
# The default value is 5 and it needs to be the same in both encode and decodefunctions.
x=input('[E]ncode or [D]ecode? answer with "e/d:" ')
if x.lower() == "e":
title = input("Enter the title of the message: ")
message = input("What is your message to encode? ")
code(title, message)
break
elif x.lower() == "d":
file_name = "encryption_key.json"
if os.path.exists(file_name):
with open(file_name, "r+") as file:
data = json.load(file)[0]
else:
print("There is no related file for decryption.")
continue
choice = input('Enter the [T]itle or the [K]ey of the message for decryption. [A]ll to decrypt everything on the file. answer with "t/k/a:" ')
if choice.lower() == 't':
title = input("Enter the title: ")
if title in data.keys():
encryption_key = data[title]
print(decode(encryption_key))
break
else:
print("There is no such title.")
elif choice.lower() == "k":
encryption_key = input("Enter the encryption code related to the message? ")
if encryption_key in data.values():
print(decode(encryption_key))
break
else:
print("There is no such encryption key.")
elif choice.lower() == "a":
decrypt_dict = {}
for k, v in data.items():
decrypt_dict[k] = decode(v)
print(decrypt_dict)
break
else:
print("There is no related file for decryption.")
else:
print("Enter a valid answer.")

Fix string index out of range

I'm trying to convert the random integer used in line 13 into a string so that it can be encrypted, but it keeps saying string index out of range on Python. I'm using the latest version of Python.
import random
result = ''
message = ''
choice = ''
key = ''
number = random.randint(1,50)
while choice != '2':
choice = input("would you like to 1. encrypt message or 2. exit ")
if choice == '1':
message = input("enter message to be encrypted ")
for i in range(0, len(message)):
result = result + chr(ord(message[i]) - number)
number = str(number)
for i in range(0, len(number[i])):
key = key key + int(ord(number[i])-7)
print(result + " press enter to close")
print(key)
end = input()
break
I think you have an issue with line number 16.
for i in range(0, len(number[i])):
'i' can only be accessible inside the loop's scope. len(number[i]) does not make sense for compiler and hence an index error.
Instead try for:
for i in range(len(number)):
Best Regards

How to loop a code in Python?

I have this Caesar's Cipher code in Python to encrypt some messages quickly, and show it to my classmates.
I have everything done, except something...
I want to make a 'Do you want to encrypt another message?' option, but I can't loop the code.
How can I loop the whole code? I'm using Python 3.5.1.
Here's my code:
print('QuantumShadow\'s Caesar Cipher')
message = input('Write your message here: ')
print('The encryption key is: ')
key = int(input())
print('Do you want to encrypt or decrypt?')
mode = input()
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
translated = ''
message = message.upper()
for symbol in message:
if symbol in LETTERS:
num = LETTERS.find(symbol)
if mode == 'encrypt':
num = num + key
elif mode == 'decrypt':
num = num - key
if num >= len(LETTERS):
num = num - len(LETTERS)
elif num < 0:
num = num + len(LETTERS)
translated = translated + LETTERS[num]
else:
translated = translated + symbol
print(translated)
print('Do you want to encrypt\\decrypt another message?')
print('Here is where I want to make the loop')
print('Coded with Python by QuantumShadow.')
One way to do it is using a while loop that goes on forever (until you break out of it):
while True:
# The rest of your code
if not input("Do you want to encrypt or decrypt another message [y/n]? ").lower().startswith("y"):
break
print("Coded with Python by QuantumShadow.")
The simplest way would be to put the whole code inside a 'while running' loop, and in the end of the loop ask if the person wants to run the code again, if not, change running to False.
Before
print("Hello World!")
After
running = True
while running:
print("Hello World!")
answer = input("Would you like to run again? (y/N)")
if answer != 'y':
running = False
But the right way to do it would be to divide your code into functions, so the final result would be cleaner and easier to read.
After the print of the title line start the while loop
ask = True
while ask: # this was initialized to True
message = input('Write your message here: ')
key = int(input('The encryption key is: '))
mode = input('Do you want to encrypt or decrypt?')
# put the coding logic here
next = input('Do you want to encrypt\\decrypt another message?')
if next.lower() == 'no':
ask = False
print('You have finished all messages')
#APerson's solution works fine. Try it out.
while True:
print('QuantumShadow\'s Caesar Cipher')
message = input('Write your message here: ')
print('The encryption key is: ')
key = int(input())
print('Do you want to encrypt or decrypt?')
mode = input()
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
translated = ''
message = message.upper()
for symbol in message:
if symbol in LETTERS:
num = LETTERS.find(symbol)
if mode == 'encrypt':
num = num + key
elif mode == 'decrypt':
num = num - key
if num >= len(LETTERS):
num = num - len(LETTERS)
elif num < 0:
num = num + len(LETTERS)
translated = translated + LETTERS[num]
else:
translated = translated + symbol
print(translated)
if input("Do you want to encrypt or decrypt another message [yes/no]? ") != "yes":
break
print("Coded with Python by QuantumShadow.")
Also consider moving print(translated) to outside of the for loop so the program only displays the final encrypted result.
put this code above your code:
x=1
while x==1:
Your Code after indent
#Add the following lines below
x=input("Press to send another message or any other key to exit")
the above method is a simple one and needs little modification to your existing code. Hope it helps!
print('QuantumShadow\'s Caesar Cipher')
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
#Wrap your code
def get_message():
message = input('Write your message here: (input q to quit)')
if message == 'q':
return message
print('The encryption key is: ')
key = int(input())
print('Do you want to encrypt or decrypt?')
mode = input()
translated = ''
message = message.upper()
for symbol in message:
if symbol in LETTERS:
num = LETTERS.find(symbol)
if mode == 'encrypt':
num = num + key
elif mode == 'decrypt':
num = num - key
if num >= len(LETTERS):
num = num - len(LETTERS)
elif num < 0:
num = num + len(LETTERS)
translated = translated + LETTERS[num]
else:
translated = translated + symbol
return translated
#loop your code
while True:
message = get_message()
if message == 'q':
break
print (message)

Caesar Cipher issue

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.

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