Python issue when reading from a file [closed] - python

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.

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.")

Getting the Value returned from a Loop to print() only once

When trying to retrieve the decrypted password for the second choice, I can't keep the program from printing Does Not Compute no matter whether the website entered is true or not. It prints twice when it is untrue so this leads me to believe the it's printing for i in the range(len(passwords)) which is 2.
How do I get it to print just the password or Does Not Compute once and not have it iterate again? I'm trying to check if the input is equal to the website but it still prints iterates twice.
import csv
import sys
# The password list - We start with it populated for testing purposes
passwords = [["yahoo", "XqffoZeo"], ["google", "CoIushujSetu"]]
# The password file name to store the passwords to
passwordFileName = "samplePasswordFile"
# The encryption key for the caesar cypher
encryptionKey = 16
# Caesar Cypher Encryption
def passwordEncrypt(unencryptedMessage, key):
# We will start with an empty string as our encryptedMessage
encryptedMessage = ""
# For each symbol in the unencryptedMessage we will add an encrypted symbol into the encryptedMessage
for symbol in unencryptedMessage:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord("Z"):
num -= 26
elif num < ord("A"):
num += 26
elif symbol.islower():
if num > ord("z"):
num -= 26
elif num < ord("a"):
num += 26
encryptedMessage += chr(num)
else:
encryptedMessage += symbol
return encryptedMessage
def loadPasswordFile(fileName):
with open(fileName, newline="") as csvfile:
passwordreader = csv.reader(csvfile)
passwordList = list(passwordreader)
return passwordList
def savePasswordFile(passwordList, fileName):
with open(fileName, "w+", newline="") as csvfile:
passwordwriter = csv.writer(csvfile)
passwordwriter.writerows(passwordList)
prompt_msg = """
What would you like to do:
1. Open password file
2. Lookup a password
3. Add a password
4. Save password file
5. Print the encrypted password list (for testing)
6. Quit program
Please enter a number (1-4)
"""
while True:
print(prompt_msg)
choice = input()
if choice == "1": # Load the password list from a file
passwords = loadPasswordFile(passwordFileName)
elif choice == "2": # Lookup at password
print("Which website do you want to lookup the password for?")
for keyvalue in passwords:
print(keyvalue[0])
print("----")
passwordToLookup = input()
for i in range(len(passwords)):
print(f"i={i}, store_info={passwords[i]}, website={passwords[i][0]}")
if passwordToLookup == passwords[i][0]:
password = passwordEncrypt(passwords[i][1], -(encryptionKey))
print(f"=> The password is {password}.")
else:
print("=> Does not compute!")
elif choice == "3":
print("What website is this password for?")
website = input()
print("What is the password?")
unencryptedPassword = input()
unencryptedPassword = passwordEncrypt(unencryptedPassword, encryptionKey)
newList = [website, unencryptedPassword]
passwords.append(newList)
print("Your password has been saved.")
elif choice == "4": # Save the passwords to a file
savePasswordFile(passwords, passwordFileName)
elif choice == "5": # print out the password list
for keyvalue in passwords:
print(", ".join(keyvalue))
elif choice == "6": # quit our program
sys.exit()
print()
print()
####### YOUR CODE HERE ######
# You will need to find the password that matches the website
# You will then need to decrypt the password
#
# 1. Create a loop that goes through each item in the password list
# You can consult the reading on lists in Week 5 for ways to loop through a list
#
# 2. Check if the name is found. To index a list of lists you use 2 square backet sets
# So passwords[0][1] would mean for the first item in the list get it's 2nd item (remember, lists start at 0)
# So this would be 'XqffoZeo' in the password list given what is predefined at the top of the page.
# If you created a loop using the syntax described in step 1, then i is your 'iterator' in the list so you
# will want to use i in your first set of brackets.
#
# 3. If the name is found then decrypt it. Decrypting is that exact reverse operation from encrypting. Take a look at the
# caesar cypher lecture as a reference. You do not need to write your own decryption function, you can reuse passwordEncrypt
#
# Write the above one step at a time. By this I mean, write step 1... but in your loop print out every item in the list
# for testing purposes. Then write step 2, and print out the password but not decrypted. Then write step 3. This way
# you can test easily along the way.
#
It seems like you want to print does not compute only if NONE of the stored passwords match the input; but as it is, you're printing that message for EACH password that doesn't match (even if some other password did match).
I've modified your loop to break when a match is found, and only print the message if no matches were found (by adding an else clause to the for loop, which executes only if the loop makes it all the way to the end.)
passwordToLookup = input()
for i in range(len(passwords)):
if passwordToLookup == passwords[i][0]:
webSite = passwordEncrypt(passwords[i][1],-(encryptionKey))
print()
print('The password is ' + webSite+'.')
print(i)
print(passwords[i])
print(passwords[i][0])
break
else:
# if we got to the end of the loop, no passwords matched
print('Does not compute!')
First, I took the liberty to reformat and improve your code to look a bit nicer.
Multi-line string for the prompt
F-string to print variables (Python 3.4 and above)
Formatting with the new black module
Your problem is that you loop through all the stored websites
for i in range(len(passwords)):
if passwordToLookup == passwords[i][0]:
...
else:
...
Actually what you should do is
Checking if the website exists in the current list
Return decrypted password if found, and Cannot computer otherwise
The best way to do 1. is to:
Transform the tuples of passwords to a dictionary: passwords = {"yahoo":"XqffoZeo", "google":"CoIushujSetu"}
Check if website is one of the keys: if website in passwords.keys(): ...
Update the rest of the code accordingly (as the list of passwords is not a list of tuples but a dictionary)
Or more simply: just transform the list of tuples to a dictionary when extracting the password:
elif choice == "2": # Lookup at password
print("Which website do you want to lookup the password for?")
for keyvalue in passwords:
print(keyvalue[0])
print("----")
passwordToLookup = input()
dict_passwords = dict(passwords)
if passwordToLookup in dict_passwords:
encrypted = dict_passwords[passwordToLookup]
password = passwordEncrypt(encrypted, -(encryptionKey))
print(f"=> The password is {password}.")
else:
print("=> Does not compute!")

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 would I write a program that can call a variable from another def?

So I set out to make a simple game of hangman and everything worked fine, the whole code worked but it lacked the ability to allow the user to replay when the game is over. Thus I set out to put all the code I have written in various functions. So that I can call the functions when they are required (I thought it was the most logical way to allow replay-ability). Various problems followed but one stood out.
The main culprit (I think) is that I could not successfully get a value to update globally. I've read similar questions on the site but could not successfully adapt it to my case. I have a sample code to show what exactly I mean:
def GameMode():
choice = input('Play alone or play with friends? A F : ')
choice = choice.upper()
if choice == 'A':
wordslotmachine = ['stand','emerald','splash']
word = random.choice(wordslotmachine)
word = word.upper()
Rules()
elif choice == 'F':
word = input('Enter your word for your friends to guess: ')
word = word.upper()
Rules()
else:
choice = input('Please enter A or F: ')
choice = choice.upper()
I would need the program to remember what the value of "word" is and use this word in another method (this method is ran by another method showed below "Rules()"):
def MainGame():
guesses = ''
turns = 10
underscore = 0
seconds = 1
checker = 0
cheaterchance = 5
while turns > 0: #check if the turns are more than zero
for char in word: # for every character in secret_word
if char in guesses: # see if the character is in the players guess
print(char+' ', end='')
else:
print('_ ', end='')# if not found, print a dash
underscore += 1
if underscore == 0:
print(': You got it!')
Wait()
NewGame()
break
#A block of if's to check for cheating
if guess not in word:
print('Your guesses so far: '+guesses)
turns -= 1
if turns == 0:
break
else:
print('')
print('Try again. You have',turns,'more guesses')
print('Delayed chance to answer by',seconds,'seconds')
counter = 1
print(0,'.. ', end='')
while counter < seconds:
time.sleep(1)
print(counter,'.. ', end='')
counter += 1
if counter == seconds:
time.sleep(1)
print(counter,'.. done!', end='')
print('')
print('')
seconds += 1
underscore = 0
else:
print('Your guesses so far: '+guesses)
underscore = 0
#The else portion of the code to check for cheating
I have tried defining "word" outside of the function. Doing this doesn't fix the problem, GameMode() will not successfully update the value of "word". And whatever the value of "word" defined outside of the function will be called and used by MainGame(). However doing this shows another problem.
That being, the code that previously worked (it successfully read the input and correctly updated the game status) now does not work. Even if the correct letter is entered by the user, the program reads the input as incorrect.
These are the two problems I have faced so far and have yet to find a way to overcome them.
Note: I have successfully created a way to make the game replay-able by putting the entire original code (without the functions) inside a while loop. However I would still very much like to know how I can get the code to work using functions.
Edit: This is the function for Rules():
def Rules():
#Bunch of prints to explain the rules
MainGame()
print('Start guessing...')
Wait() is just a delay function with a countdown.
Global vs. Local variables.
You can reference and use a global variable from within a function, but you cannot change it.
It's bad practice, but you CAN declare a variable within your function to be global and then changes to it inside your function will apply to the variable of the same name globally.
HOWEVER, what I suggest is to return the word at the end of your function.
def whatever_function(thisword):
do some stuff
return word
new_word = whatever_function(thisword)
Functions can, and usually should, return values. Make GameMode() return the word to the caller;
def GameMode():
choice = input('Play alone or play with friends? A F : ')
choice = choice.upper()
if choice == 'A':
wordslotmachine = ['stand','emerald','splash']
word = random.choice(wordslotmachine)
word = word.upper()
Rules() #ignore this
elif choice == 'F':
word = input('Enter your word for your friends to guess: ')
word = word.upper()
Rules() #ignore this
else:
choice = input('Please enter A or F: ')
choice = choice.upper()
return word
From the main call GameMode and save the word;
def MainGame():
guesses = ''
turns = 10
underscore = 0
seconds = 1
checker = 0
cheaterchance = 5
word = GameMode() # add this here
You almost certainly want to use a class with instance variables
Contrived example:
class Hangman:
def __init__(self):
print("Starting hangman")
def mode(self):
# ...
self.word = 'whatever'
def play(self):
print("Look i have access to word", self.word)
if __name__ == '__main__':
hm = Hangman()
hm.mode()
hm.play() # may be what you want to put in a while loop
To access a global variable from inside a function, you have to tell python that it is global:
my_global_var = 1
def some_func():
global my_global_var
You have to use global keyword in every method that the global variable is being used or python will think you are defining/ using a local variable
Having said that, you should avoid globals as a coding practise.
global word #probably define this after imports.
def GameMode():
global word #add this
choice = input('Play alone or play with friends? A F : ')
choice = choice.upper()
if choice == 'A':
wordslotmachine = ['stand','emerald','splash']
word = random.choice(wordslotmachine)
word = word.upper()
Rules() #ignore this
elif choice == 'F':
word = input('Enter your word for your friends to guess: ')
word = word.upper()
Rules() #ignore this
else:
choice = input('Please enter A or F: ')
choice = choice.upper()
def MainGame():
guesses = ''
turns = 10
underscore = 0
seconds = 1
checker = 0
cheaterchance = 5
global word # add this here
use the code
global word
above the def or let the def return the value of word so it is stored in a variable outside the def

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)

Categories

Resources