How to loop a code in Python? - 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)

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

Python issue when reading from a file [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Hello so i was doing a school project and I wrote this out I got it all working so my next task was to make it to read the message from an file so i changed the definition where it asked for the message which is UserMessage() so i run the code it works it prints out whats in the text file but when i do the last bit where it gets the final answer it shows this error
Traceback (most recent call last):
File "C:\Users\christian\Desktop\Python\2 keywor with cypher code.py", line 138, in <module>
Restart()
File "C:\Users\christian\Desktop\Python\2 keywor with cypher code.py", line 127, in Restart
Text = TranslateMessage2(Key2, Message2, Option)
File "C:\Users\christian\Desktop\Python\2 keywor with cypher code.py", line 107, in TranslateMessage2
Translated.append(symbol) # The symbol was not in LETTERS, so add it to translated as is.
NameError: name 'Translated' is not defined
import pyperclip
Valid_Letters = 'ZABCDEFGHIJKLMNOPQRSTUVWXY' # This is where it stores the Letters witch are being used in the program
def Linespacer():
print('================================================================')
def GetOption(): # This is the first queston in the program witch is asking if they want to encrypt decrypt
while True:
print('Do you wish to encrypt or decrypt a message?')
Option = input().lower()
if Option in 'encrypt e decrypt d'.split():
return Option # This is where if the user does not enter the right ifomation it goes back tot he top and ask the question
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d".') # If the user doers not enter the right thing for example if they enter an 'l' it prints that message
def UserMessage():
mes = str(input('would you like to encrypt or decrypt from a file or type your own message?(file/f or message/m): '))
if mes == 'f' or mes == 'file':
name = str(input("What is the document you want to read called?: "))
with open(name, "rt") as in_file:
text = in_file.read()
print(text)
return text
if mes == 'm' or mes == 'message':
text = str(input('Enter your message: '))
def UserKeyword(): # This def is what ask the user for the Message and gathers the infomation
print('Enter your First keyword:') # Prints out the message asking for the keyword
return input()
def UserKeyword2(): # This def is what ask the user for the Message and gathers the infomation
print('Enter your Second keyword:') # Prints out the message asking for the keyword
return input()
def TranslateMessage(Key, Message, Option): # This is the main def and where it does all of the maths when you call the def it reqires 3 Variables
Translated = [] # stores the encrypted/decrypted message string
keyIndex = 0 # This is the defult keyIndex when the program is started
Key = Key.upper() # This is allowing the user to have Upper case letters or lowercase letters
for symbol in Message: # loop through each character in message
num = Valid_Letters.find(symbol.upper()) #
if num != -1: # -1 means symbol.upper() was not found in LETTERS
if Option == 'encrypt' or Option == 'e':
num += Valid_Letters.find(Key[keyIndex]) #This makes it so if they are encrypting it adds
elif Option == 'decrypt' or Option == 'd':
num -= Valid_Letters.find(Key[keyIndex]) # This makes it so if they are decrypting it subtract
num %= len(Valid_Letters)
if symbol.isupper():
Translated.append(Valid_Letters[num])
elif symbol.islower():
Translated.append(Valid_Letters[num].lower())
keyIndex += 1 # move to the next letter in the key
if keyIndex == len(Key):
keyIndex = 0
else:
Translated.append(symbol) # The symbol was not in LETTERS, so add it to translated as is.
return ''.join(Translated) # It joins all of the functions together so the user can have all of the text together
def TranslateMessage2(Key2, Message2, Option): # This is the main def and where it does all of the maths when you call the def it reqires 3 Variables
Translated2 = [] # stores the encrypted/decrypted message string
keyIndex = 0 # This is the defult keyIndex when the program is started
Key2 = Key2.upper() # This is allowing the user to have Upper case letters or lowercase letters
for symbol in Message2: # loop through each character in message
num = Valid_Letters.find(symbol.upper()) #
if num != -1: # -1 means symbol.upper() was not found in LETTERS
if Option == 'encrypt' or Option == 'e':
num += Valid_Letters.find(Key2[keyIndex]) #This makes it so if they are encrypting it adds
elif Option == 'decrypt' or Option == 'd':
num -= Valid_Letters.find(Key2[keyIndex]) # This makes it so if they are decrypting it subtract
num %= len(Valid_Letters)
if symbol.isupper():
Translated2.append(Valid_Letters[num])
elif symbol.islower():
Translated2.append(Valid_Letters[num].lower())
keyIndex += 1 # move to the next letter in the key
if keyIndex == len(Key2):
keyIndex = 0
else:
Translated.append(symbol) # The symbol was not in LETTERS, so add it to translated as is.
return ''.join(Translated2) # It joins all of the functions together so the user can have all of the text together
def PlayAgainMessage():
again = str(input("Would you like to restart Y or N: "));
Linespacer()
if again == "Y" or again == "y": # This is an if statment it is saying that if the user types "Y" it runs the code to restart the program
Restart(); # If the user types "N" it Exits the program
elif again == "N" or again == "n":
exit()
def Restart(): # This is the def which allows the user to restart the prgram once they have done it
Option = GetOption()
Message = UserMessage()
Key = UserKeyword()
Key2 = UserKeyword2()
Message2 = TranslateMessage(Key, Message, Option)
Text = TranslateMessage2(Key2, Message2, Option)
Linespacer()
print('Your translated text is: %s' % Text) # Prints the message and get the text which has been encrypt or decrypt
pyperclip.copy(Text)
Linespacer()
name = str(input("What would you like to name the File: "))
name1 = str;
file = open(name+".txt", "w")
file.write(Text)
file.close()
PlayAgainMessage()
Restart()
You left a Translated in your TranslateMessage2 when you probably meant to change it to Translated2.
In TranslateMessage2:
Translated.append(symbol)
Should be:
Translated2.append(symbol)
You defined Translated in TranslateMessage but not in TranslateMessage2
As a result Translated does not exist within the global namespace, nor the namespace of TranslateMessage2.
Assuming you intentionally wanted to append to Translated and not Translated2 you either need to make Translated global variable or assign it to a variable through your TranslateMessage function.
To make Translated global you simply need to initialise it outside of the function.

Syntax Error Python 3.3.3 No Reason Given

my program keeps throwing up a syntax error with no reason given with this code and I cannot figure out why for the life of me. I've deduced that the error-causing lines are the ones I have hashed-out
#char = ord(message[i])-96
#key = ord(keyword[i])-96
They are in lines 15 and 16 of the code. Please help me!!!
option = input("Do you want to encrypt or decrypt? (E/D): ")
keyword = input("Enter your keyword: ")
message = input("Enter your message: ")
while len(keyword)<len(message):
keyword=keyword+keyword
keyword=keyword[:len(message)]
newMessage = ""
for i in range(len(message)):
char = ord(message[i])
key = ord(keyword[i])
if char==32:
newMessage = newMessage+" "
elif char<97 or char>122:
message = input("Enter your message: ")
#char = ord(message[i])-96
#key = ord(keyword[i])-96
elif option == "E":
if char+key>26:
newMessage = newMessage+chr(char+key-26)
else:
newMessage = newMessage+chr(char+key)
else:
if char-key<1:
newMessage = newMessage+chr(char-key+26)
else:
newMessage = newMessage+chr(char-key)
print(newMessage)
You are ending your if and subsequent elif with those two lines. As a result, elif option == "E": makes no sense as there is no preceding if statement before it. You either have to indent:
elif char<97 or char>122:
message = input("Enter your message: ")
char = ord(message[i])-96
key = ord(keyword[i])-96
Or begin a new if statement with your subsequent elif:
if option == "E":
if char+key>26:
newMessage = newMessage+chr(char+key-26)
else:
newMessage = newMessage+chr(char+key)
You have not indented (put 4 space before) the two lines. As your are in a if statement you have to put them.

Why doesn't my 'oldUser()' run and why does it start again all the time?

I'm very very new to programming and for a school project (50% of my final grade) I had to create a Python program that did roughly this.
I've had some help from my older brother and my teacher but mainly did it myself with some flow charts etc, so please forgive me if I haven't followed conventional rules and things of this nature, or if my code is messy. I will finalise it, just needed bait of help/support from the pro's.
This is my code and I have an issue with it. Once I have pressed 'y' and then 'y' again on the displayMenu() why doesn't it run oldUser()
Also, if any of you have any suggestion on what could make my code better, or I could improve it would be very helpful and I will take it on board.
import os # allows me to use functions defined elsewhere. os module allows for multi platforming.
import sys
words = []
users = {}
status = ""
def teacher_enter_words():
done = False
print 'Hello, please can you enter a word and definition pair.'
while not done:
word = raw_input('\nEnter a word: ')
deff = raw_input('Enter the definition: ')
# append a tuple to the list so it can't be edited.
words.append((word, deff))
add_word = raw_input('Add another word? (y/n): ')
if add_word.lower() == 'n':
done = True
def student_take_test():
student_score = 0
for pair in words:
print 'Definition:', pair[1]
inp = raw_input('Enter word: ')
student_score += check_error(pair[0], inp)
print 'Correct spelling:', pair[0], '\n'
print 'Your score:', student_score
def check_error(correct, inputt):
len_c = len(correct)
len_i = len(inputt)
# threshold is how many incorrect letters do we allow before a
# minor error becomes a major error.
# 1 - allow 1 incorrect letter for a minor error ( >= 2 becomes major error)
threshold = 1
# immediately check if the words are the same length
num_letters_incorrect = abs(len_c - len_i) # abs() method returns value of x - positive dist between x and zero
if num_letters_incorrect == 0:
for i in xrange(0, len(correct)):
if correct[i] != inputt[i]:
num_letters_incorrect += 1
if num_letters_incorrect <= threshold:
if num_letters_incorrect == 0:
return 2 # no incorrect letter.
else:
return 1 # minor error.
else:
return 0 # major error.
def displayMenu():
status = raw_input('Are you a registered user? y/n?: ')
if status == raw_input == 'y':
oldUser()
elif status == 'n':
newUser()
def newUser():
createLogin = raw_input('Create login name: ')
if createLogin in users:
print '\nLogin name already exist!\n'
else:
createPassw = raw_input('Create password: ')
users[createLogin] = createPassw
print '\nUser created!\n'
def oldUser():
login = raw_input('Enter login name: ')
passw = raw_input('Enter password: ')
if login in users and users[login] == passw:
print '\nLogin successful!\n'
else:
print "\nUser doesn't exist or wrong password!\n"
if __name__ == '__main__':
running = True
while running:
os.system('cls' if os.name == 'nt' else 'clear') # multi-platform, executing a shell command
reg = raw_input('Do you want to start the program? y/n?').lower()
if reg == 'y' or reg == 'yes':
displayMenu()
else: sys.exit(0)
inp = raw_input('Are you a Teacher or a Student? (t/s): ').lower()
if inp == 't' or inp == 'teacher':
teacher_enter_words()
else:
student_take_test()
running = False
raw_input is a function. status == raw_input == 'y' will never be true: that is comparing status with the function, and with 'y'.
I suspect that's simply a typo, and you just meant if status == 'y':

Categories

Resources