So, I’m stuck with separating the multiple loops.
The first cycle works fine. And the second one too. But not the two last ones. When I’m trying to type the DNA or Protein, it only gives an answer: Restart? Y \ N
My code:
while True:
A = (input())
if A == ("Start"):
print ("What type of the data you want to process?")
print ("DNA", "RNA", "Protein", sep="\n")
break
else:
print ("Incorrect input")
continue
break
while True:
X = (input())
if X == ("RNA"):
print ("What you want to do with RNA?", "RNA to DNA? RNA to Protein? seqRNA length?", sep="\n?")
continue
break
else:
print("Restart?", "Y \ N", sep="\n")
continue
break
while True:
Y = (input())
if Y == ("DNA"):
print ("What you want to do with DNA?", "DNA to RNA? seqDNA length?", sep="\n")
continue
break
else:
print("Anything else?", "Yes No", sep="\n")
continue
break
while True:
Z = (input())
if Z == ("Protein"):
print ("What you want to do with Protein?", "Protein to RNA? protein Name?", sep="\n")
continue
break
else:
print("Anything else?", "Yes No", sep="\n")
continue
break
I’m already tried to delete one of these cycles and tried to run it, but the results were the same. I had searched for the examples of using break, while and if, but found answers only for just the only one loop, not multiple. I find it quite dissapointing, because I’ve wanted to do this for a better understanding of the python. And not just using a BioPython library. But ironically, just the process of the transcription, reverse transcription, translation, translation to RNA, or sequence length calculation is not a big problem. It’s all needs just a one line of the code.
I’ve cleaned up and restructured your code a bit. Is this what you wanted?
while True:
print("What type of the data you want to process?")
A = input("DNA, RNA, Protein > ")
if A == "DNA":
print("What you want to do with DNA?")
Y = input("DNA to RNA? seqDNA length? > ")
# Test and do something with Y
elif A == "RNA":
print("What you want to do with RNA?")
X = input("RNA to DNA? RNA to Protein? seqRNA length? > ")
# Test and do something with X
elif A == "Protein":
print("What you want to do with Protein?")
Z = input("Protein to RNA? protein Name? > ")
# Test and do something with Z
else:
print("Incorrect input")
continue
# If user wants to restart, stay in the loop, else break.
if input("Restart? Y \ N > ") == "N":
break
The problem is with the continue statements once you get passed the Start condition and rna/dna/protein condition.
I only tested for RNA but I removed the continue statement after the print and it seemed to work
what is your intention with the continue there?
Additionally, using so many while true loops and relying on break and continue isn't really best practice idt. I would use do something like use A as input at the very top and your conditions could be something like `while A not in ["RNA", "DNA", PROTEIN"] or something like that and that way it'll keep looping and asking for input until correct one is passed
finally, I would cast every input to be uppercase or lowercase (and your conditional checks too ) that way you can avoid input errors based on case issues
while True:
print("What type of the data you want to process?", "RNA? DNA?", sep = "\n")
A = input("")
if A == "RNA":
print("What you want to do with RNA?", "(a1)RNA to Protein? (a2)RNA to DNA? (a3)RNA Length? (a4)RNA Splicing? (a5)RNA nucleotides (a6)ratio? RNAi? ", sep = "\n")
break
if A == "DNA":
print("What you want to do with DNA", "(b1)DNA to RNA? (b2)DNA length? (b3)DNA nucleotides ratio? (b4)Complimentary DNA chain?", sep = "\n")
break
else:
print("Nope") #TF2 references
continue
while A == "RNA":
X = input("")
if X == "a1":
print("Input RNA")
import ptranslation #Written by myself module for RNA translation
RNA_translation = input("")
print (RNA_translation)
break
if X == "a2":
print("Input RNA")
RNA_seq = input("")
DNA_seq = RNA_seq.replace("U", "T")
print (DNA_seq)
break
if X == "a3":
print ("Input RNA")
RNA = input("")
RNAo = int (len(RNA)//2)
print(RNAo)
break
if X == "a4":
print ("Input RNA")
import re
RNA = input("")
regex = r"GU(?:\w{0,}?)AG" #regex black magic Uga-Buga, still need to undestand it better
exons = re.sub(regex, '', RNA)
print(exons)
break
if X == ("a5"):
print("Input RNA")
RNAn = input ("")
X = (RNAn.count("A")) + (RNAn.count("U")) + (RNAn.count("C")) + (RNAn.count ("G"))
A = (RNAn.count("A")/X)
U = (RNAn.count("U")/X)
G = (RNAn.count("G")/X)
C = (RNAn.count("C")/X)
print ("A =", A, "U =", U, "G =", G, "C =", C)
break
if X == ("a6"):
print("Input RNA")
N = input("")
print(N.translate(str.maketrans({"A": "U", "G": "C", "U": "A", "C": "G"})))
break
else:
print("NOPE! Input correct option!")
continue
break
while A == "DNA":
Y = input("")
if Y == "b1":
print ("Input DNA ")
DNA_seq = input("")
RNA_seq = DNA_seq.replace("T", "U")
print (RNA_seq)
break
if Y == ("b2"):
print("Input DNA")
DNA = input("")
DNAo = int (len(DNA)//2)
print(DNAo)
break
if Y == ("b3"):
print("Input DNA")
DNAn = input ("")
X = (DNAn.count("A")) + (DNAn.count("T")) + (DNAn.count("C")) + (DNAn.count ("G"))
A = (DNAn.count("A")/X)
T = (DNAn.count("T")/X)
G = (DNAn.count("G")/X)
C = (DNAn.count("C")/X)
print ("A =", A, "T =", T, "G =", G, "C =", C)
break
if Y == ("b4"):
print("Input DNA")
Nd = input("")
print(Nd.translate(str.maketrans({"A": "T", "G": "C", "T": "A", "C": "G"})))
break
else:
print("NOPE! Input correct option!")
continue
break
#psyhological support in process of the coding - M.Kashtanov
Related
Hello How can i force to make the nname to only string input because even though i put number it still continue to the next function and i only like it to be a name of the people nname= str(input()) does not work thats why im asking if there is other alternative to make it work with only a string
print("Good Day Welcome To our Shop.")
mnu = ["Milktea","Foods", "Drinks", "Dessert"]
lsa = ["1.Matcha", "Taro", "Winter Melon", "Okinawa", "Chocolate",
"Cheese Cake"]
fds = {'Chicken'}
shot = ["tubig"]
mtms = ["ice cream"]
laht = []
print("Hi what would you like to be called, "
"So we can inform you if your order is ready")
def cstmrinfo(name):
print("Okay " + name, "So what would you like to get " )
print(*mnu,sep = "\n")
nname= input().lower()
def kuha_order():
while True:
order = input()
if (order == "Milktea") or (order == "milktea"):
print(lsa)
laht.append(order)
break
elif (order == "Foods") or (order == "foods"):
print(fds)
laht.append(order)
break
elif (order == "Drinks") or (order == "drinks"):
print(shot)
laht.append(order)
break
elif (order == "Dessert") or (order == "dessert"):
print(mtms)
laht.append(order)
break
else:
print("Sorry you input a thing that is not available on our menu, "
"Please Try again:")
continue
def pnglhtn():
while True:
print("I Would like to get a: ")
qwe = input()
if qwe in lsa:
print(qwe)
elif qwe in fds:
print(qwe)
elif qwe in shot:
print(qwe)
elif qwe in mtms:
print(qwe)
else:
print("There is no such thing like that ")
continue
dmi = int(input("How Many Servings Would you Like: "))
laht.append(qwe)
laht.append(dmi)
print("So " + pngln, "you Like a " + str(laht[:2]))
print (dmi, "Serves of: " + str(laht[:2]))
break
cstmrinfo(nname)
kuha_order()
pnglhtn()
You can use either lower() or upper(). Please check the following answer:
if order.lower()=="milktea":
print(flvrs)
laht.append(order)
break
OR
if order.upper()=="MILKTEA":
print(flvrs)
laht.append(order)
break
When using the logical "or" operator in an if...else statement in python you have to repeat the variable as well as the value (i know that sounds confusing so look at the example)
this means that this won't work:
if order == "Milktea" or "milktea":
the correct formation should be:
if (order == "Milktea") or (order == "milktea"):
alternatively if you want to simply check one variable against a range of values check out the match...case statements in python 3.10+: https://learnpython.com/blog/python-match-case-statement/
######################################################
Remove the if order in mmu line and indent the corresponding else (code listed below)
def kuha_order():
while True:
order = input()
print(order)
if order == "Milktea":
print(flvrs)
laht.append(order)
break
elif order == "Foods":
print(pgkn)
laht.append(order)
break
elif order == "Drinks":
print(shot)
laht.append(order)
break
elif order == "Dessert":
print(mtms)
laht.append(order)
break
else:
print("Sorry you input a thing that is not available on our menu")
continue
you can combine this with my answer above to get what you need :)
I'm new to Python and I am trying to create a simple calculator. Sorry if my code is really messy and unreadable. I tried to get the calculator to do another calculation after the first calculation by trying to make the code jump back to while vi == true loop. I'm hoping it would then ask for the "Enter selection" again and then continue on with the next while loop. How do I do that or is there another way?
vi = True
ag = True
while vi == True: #I want it to loop back to here
op = input("Input selection: ")
if op in ("1", "2", "3", "4"):
vi = False
while vi == False:
x = float(input("insert first number: "))
y = float(input("insert Second Number: "))
break
#Here would be an If elif statement to carry out the calculation
while ag == True:
again = input("Another calculation? ")
if again in ("yes", "no"):
ag = False
else:
print("Please input a 'yes' or a 'no'")
if again == "no":
print("Done, Thank you for using Calculator!")
exit()
elif again == "yes":
print("okay!")
vi = True #I want this part to loop back
Nice start. To answer your question about whether there's another way to do what you're looking for; yes, there is generally more than one way to skin a cat.
Generally, I don't use while vi==True: in one section, then follow that up with while vi==False: in another since, if I'm not in True then False is implied. If I understand your question, then basically a solution is to nest your loops, or call one loop from within the other. Also, it seems to me like you're on the brink of discovering the not keyword as well as functions.
Code
vi = True
while vi:
print("MENU")
print("1-Division")
print("2-Multiplication")
print("3-Subtraction")
print("4-Addition")
print("Any-Exit")
op = input("Input Selection:")
if op != "1":
vi = False
else:
x = float(input("insert first number: "))
y = float(input("insert Second Number: "))
print("Placeholder operation")
ag = True
while ag:
again = input("Another calculation? ")
if again not in ("yes", "no"):
print("Please input a 'yes' or a 'no'")
if again == "no":
print("Done, Thank you for using Calculator!")
ag = False
vi = False
elif again == "yes":
print("okay!")
ag = False
Of course, that's a lot of code to read/follow in one chunk. Here's another version that introduces functions to abstract some of the details into smaller chunks.
def calculator():
vi = True
while vi:
op = mainMenu()
if op == "\n" or op == " ":
return None
x, y = getInputs()
print(x + op + y + " = " + str(eval(x + op + y)))
vi = toContinue()
return None
def mainMenu():
toSelect=True
while toSelect:
print()
print("\tMENU")
print("\t/ = Division; * = Multiplication;")
print("\t- = Subtract; + = Addition;")
print("\t**= Power")
print("\tSpace or Enter to Exit")
print()
option = input("Select from MENU: ")
if option in "/+-%** \n":
toSelect = False
return option
def getInputs():
inpt = True
while inpt:
x = input("insert first number: ")
y = input("insert second number: ")
try:
tmp1 = float(x)
tmp2 = float(y)
if type(tmp1) == float and type(tmp2) == float:
inpt = False
except:
print("Both inputs need to be numbers. Try again.")
return x, y
def toContinue():
ag = True
while ag:
again = input("Another calculation?: ").lower()
if again not in ("yes","no"):
print("Please input a 'yes' or a 'no'.")
if again == "yes":
print("Okay!")
return True
elif again == "no":
print("Done, Thank you for using Calculator!")
return False
I am making a small quiz and trying to learn python. The quiz takes the first answer then loops all the way to the bottom instead of asking the user the rest of the questions. It will print the first question, then ask for the answer , then it will run throught the rest of the code but it won't actually ask for the input or anything like that.
question_1 = ("ex1")
question_2 = ("ex2")
question_3 = ("ex3")
question_4 = ("ex4")
answer = input ("Please type the letter you think is correct: ")
count = 0
# answers
print (question_1)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "b" or answer == "B":
print ("Correct")
count +=1
else:
print ("Incorrect")
print (question_2)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "a" or answer == "A":
print ("Correct")
count +=1
else:
print ("Incorrect")
print (question_3)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "d" or answer == "D":
print ("Correct")
count +=1
else:
print ("Incorrect")
print (question_4)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "c" or answer == "C":
print ("Correct")
count +=1
else:
print ("Incorrect")
You are only asking for one input and then checking that answer against every question.
You will need to add a new input for every question and then check against that input
e.g.
count = 0
print('Q1')
ans1 = input('A/B/C?')
if ans1.lower() == 'c': # Checks for it as a lowercase so no need to repeat it
print('Correct')
count += 1
else:
print('Incorrect')
print('Q2')
ans2 = input('A/B/C?')
if ans2.lower() == 'b':
print('Correct')
count += 1
else:
print('Incorrect')
You need to have the input() function after each question. An input is asked for at each input, writing it once before all the questions won't work.
By the way, you might want to use lists and a loop to get the same done with less code.
I was making code on python but it showed an asterisk where the number goes on the cell, I tried making a print program to see if it was the code but it still didn't work. Please help, this is the code.
Items = ""
Total = 0
def adding_report(report):
while True:
X = input("please input integer to add or Q to quit")
if X.isdigit() == "True":
X = int(X)
Total = Total + X
if report == "A":
Items = Items + X
elif X == "Q":
print("Your result is")
if report == "A":
print("Items")
print(Items)
print("total")
print(Total)
break
else:
print("invalid input.")
adding_report("T")
You are stuck in an infinite loop.
Moreover, you cannot compare to the string "True", but rather to True only:
if X.isdigit() == True:
Instead of:
if X.isdigit() == "True":
You can also skip the comparison to True altogether
if X.isdigit():
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am having an issue with my decryption algorithm. It outputs to a text file a huge list of repeated ((((( and other things. What's wrong with my code, and how can I fix it? I think it has something to do with the last function of the decrypting process. But I am not sure.
import sys
import os.path
def convertToNum(ch):
alpha ='''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!##$%^&()-_=+[]{}\\|;:\'",./<>?\n\t '''
index = alpha.find(ch)
return index
def Matrix(text):
evenChars = []
oddChars = []
index = 0
for ch in text:
if index % 2 == 0:
#this is an even character
evenChars.append(convertToNum(ch))
else: #this is an odd character
oddChars.append(convertToNum(ch))
index += 1
masterList = []
if (evenChars >(oddChars)):
oddChars.append(convertToNum(" "))
for i in range(len(evenChars)):
masterList.append([evenChars[i],oddChars[i]])
return masterList
def getMatrices(text):
print("A list of integers acts as a key. Each value is stored in a,b,c,d. Please enter the values for: ")
a = int(input("\nA :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
if (a*d) - (c*b) == 1:
print("Valid Key\n")
elif (a*d) - (c*b) ==-1:
print("Valid Key\n")
else:
print("Invalid Key")
sys.exit()
indList = Matrix(text)
encryptList = []
for nestList in indList:
x = nestList[0]
y = nestList[1]
encryptList.append(x*a + y*c)
encryptList.append(x*b + y*d)
return encryptList
def backtoText(text):
print("A list of integers acts as a key. Each value is stored in a,b,c,d. If you have already entered a key to encrypt, please use the same key. Please enter the values for: ")
a = int(input("\nA :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
if (a*d) - (c*b) == 1:
print("Valid Key\n")
elif (a*d) - (c*b) ==-1:
print("Valid Key\n")
else:
print("Invalid Key")
sys.exit()
keyA = ((a*d) - (c*b)) * (d)
keyB = ((a*d) - (c*b)) * (-b)
keyC = ((a*d) - (c*b)) * (-c)
keyD = ((a*d) - (c*b)) * (a)
print(keyA,keyB,keyC,keyD)
evenNums=[]
oddNums=[]
index = 0
for ch in text: #ch takes the place of the next characer in plain text
if index % 2 == 0:
evenNums.append(ch)
else:
oddNums.append(ch)
index += 1
decrypted= []
if (evenNums >(oddNums)):
oddNums.append(" ")
for i in range(len(evenNums)):
decrypted.append([evenNums[i],oddNums[i]])
indList = decrypted
decryptList = []
for nestList in indList:
x = nestList[0]
y = nestList[1]
decryptList.append(x*keyA + y*keyC)
decryptList.append(x*keyB + y*keyD)
return decryptList
def outPutString(text):
alpha = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!##$%^&*()-_=+[]{}\\|;:\'",./<>?\n\t '''
finalString =''
text = backtoText(text)
for ch in text:
finalString += alpha[ch]
return finalString
def main():
print("What would you like to do?: ")
answer = input("1) Encrypt File\n2) Decrypt File\n\n")
if answer == '1':
fileName = input("Please enter a filename to encrypt : ")
if not os.path.isfile(fileName):
print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
sys.exit()
plaintext_file = open(fileName)
text = ""
for line in plaintext_file.readlines():
text += line + "\n"
plaintext_file.close()
name =input("Please enter the file name that you want to save the encrypted file as : ")
if os.path.isfile(name) == False:
matrices = getMatrices(text)
for value in matrices:
encrypted_file.write(str(value) + "\n")
encrypted_file.close()
encrypted_file.write(str(getMatrices(text)))
encrypted_file.close()
elif os.path.isfile(name) == True:
answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
if answer2 == 'y':
encrypted_file = open(name,'w')
encrypted_file.write(str(getMatrices(text)))
encrypted_file.close()
elif answer == 'n':
print("Thank you for wasting time :D \n\n")
sys.exit()
else:
print("Invalid response. It's not hard to put y or n.\n\n")
sys.exit()
elif answer == '2':
fileName = input("Please enter a filename to decrypt : ")
if not os.path.isfile(fileName):
print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
sys.exit()
Encrypted_file = open(fileName)
text = []
for line in Encrypted_file.readlines():
text.append(line)
Encrypted_file.close()
name = input("Please enter the file name that you want to save the decrypted text saved as : ")
if os.path.isfile(name) == False:
Decrypted_file = open(name,'w')
Decrypted_file.write(str(outPutString(text)))
Decrypted_file.close()
elif os.path.isfile(name) == True:
answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
if answer2 == 'y':
Decrypted_file = open(name,'w')
Decrypted_file.write(str(outPutString(text)))
Decrypted_file.close()
elif answer == 'n':
print("Thank you for wasting time :D \n\n")
sys.exit()
else:
print("Invalid response. It's not hard to put y or n.\n\n")
sys.exit()
else:
print("Invalid Entry. The program will terminate")
sys.exit()
main()
Well this was a fun one!
in def convertToNum(ch): the alpha does not equal the alpha in def outPutString(text): (missing an *) causing (in my case) tabs instead of spaces and a ? to appear at the end of my decrypted string. I would recommend using a global variable to prevent things like this happening in the future.
Your encryption algorithm worked great and didn't need any adjustment. There were some incompatible variable types in the decryption phase but I managed to get everything to work and have included the working code (my comments marked with ##) I hope this helped.
Edit: As Eric points out in the comments, if (evenNum>(oddNum)) is probably not doing what you want it to do. According to the python docs:
Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.
I Assume you want to compare the lengths of the two arrays to make sure they are equal. If this is the case then you would want to use if (len(evenNum)>len(oddNum))
import sys
import os.path
def convertToNum(ch):
alpha ='''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!##$%^&*()-_=+[]{}\\|;:\'",./<>?\n\t ''' #you forgot your asterix
index = alpha.find(ch)
return index
def Matrix(text):
evenChars = []
oddChars = []
index = 0
for ch in text:
if index % 2 == 0:
#this is an even character
evenChars.append(convertToNum(ch))
else: #this is an odd character
oddChars.append(convertToNum(ch))
index += 1
masterList = []
if (len(evenChars) >len(oddChars)): ## comparing lengths instead of contents
oddChars.append(convertToNum(" "))
for i in range(len(evenChars)):
masterList.append([evenChars[i],oddChars[i]])
return masterList
def getMatrices(text):
print("A list of integers acts as a key. Each value is stored in a,b,c,d. Please enter the values for: ")
a = int(input("\nA :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
if (a*d) - (c*b) == 1:
print("Valid Key\n")
elif (a*d) - (c*b) ==-1:
print("Valid Key\n")
else:
print("Invalid Key")
sys.exit()
indList = Matrix(text)
encryptList = []
for nestList in indList:
x = nestList[0]
y = nestList[1]
encryptList.append(x*a + y*c)
encryptList.append(x*b + y*d)
return encryptList
def backtoText(text):
print("A list of integers acts as a key. Each value is stored in a,b,c,d. If you have already entered a key to encrypt, please use the same key. Please enter the values for: ")
a = int(input("\nA :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
if (a*d) - (c*b) == 1:
print("Valid Key\n")
elif (a*d) - (c*b) ==-1:
print("Valid Key\n")
else:
print("Invalid Key")
sys.exit()
keyA = ((a*d) - (c*b)) * (d)
keyB = ((a*d) - (c*b)) * (-b)
keyC = ((a*d) - (c*b)) * (-c)
keyD = ((a*d) - (c*b)) * (a)
print(keyA,keyB,keyC,keyD)
evenNums=[]
oddNums=[]
index = 0
newText = text[0].strip('[ ]') ## these two lines convert the string to an array
textArray = newText.split(',')
for ch in textArray: ## changed text to textArray(see above) #ch takes the place of the next characer in plain text
if index % 2 == 0:
evenNums.append(int(ch)) ## converting string number to int for later operations
else:
oddNums.append(int(ch))
index += 1
decrypted= []
if (len(evenNums) >len(oddNums)): ## comparing lengths instead of arrays
oddNums.append(" ")
for i in range(len(evenNums)):
decrypted.append([evenNums[i],oddNums[i]])
indList = decrypted
decryptList = []
for nestList in indList:
x = nestList[0]
y = nestList[1]
decryptList.append(x*keyA + y*keyC)
decryptList.append(x*keyB + y*keyD)
return decryptList
def outPutString(text):
alpha = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!##$%^&*()-_=+[]{}\\|;:\'",./<>?\n\t '''
finalString =''
text = backtoText(text)
for ch in text:
finalString += alpha[ch]
print(finalString)
return finalString
def main():
print("What would you like to do?: ")
answer = input("1) Encrypt File\n2) Decrypt File\n\n")
if answer == '1':
fileName = input("Please enter a filename to encrypt : ")
if not os.path.isfile(fileName):
print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
sys.exit()
plaintext_file = open(fileName)
text = ""
for line in plaintext_file.readlines():
text += line ##+ "\n" ##you don't need to add a new line as '\n' is already included at the end of every line.
plaintext_file.close()
name =input("Please enter the file name that you want to save the encrypted file as : ")
if os.path.isfile(name) == False:
##matrices = getMatrices(text)
##for value in matrices:
##encrypted_file.write(str(value) + "\n")
##encrypted_file.close()
## I added the line below(and removed lines above) to be consistent with your later usage
encrypted_file = open(name,'w')
encrypted_file.write(str(getMatrices(text)))
encrypted_file.close()
elif os.path.isfile(name) == True:
answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
if answer2 == 'y':
encrypted_file = open(name,'w')
encrypted_file.write(str(getMatrices(text)))
encrypted_file.close()
elif answer == 'n':
print("Thank you for wasting time :D \n\n")
sys.exit()
else:
print("Invalid response. It's not hard to put y or n.\n\n")
sys.exit()
elif answer == '2':
fileName = input("Please enter a filename to decrypt : ")
if not os.path.isfile(fileName):
print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
sys.exit()
Encrypted_file = open(fileName)
text = []
for line in Encrypted_file.readlines():
text.append(line)
Encrypted_file.close()
name = input("Please enter the file name that you want to save the decrypted text saved as : ")
if os.path.isfile(name) == False:
Decrypted_file = open(name,'w')
Decrypted_file.write(str(outPutString(text)))
Decrypted_file.close()
elif os.path.isfile(name) == True:
answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
if answer2 == 'y':
Decrypted_file = open(name,'w')
Decrypted_file.write(str(outPutString(text)))
Decrypted_file.close()
elif answer == 'n':
print("Thank you for wasting time :D \n\n")
sys.exit()
else:
print("Invalid response. It's not hard to put y or n.\n\n")
sys.exit()
else:
print("Invalid Entry. The program will terminate")
sys.exit()
main()