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()
Related
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 have spent a lot of time creating this encryption program that is specific to an assignment. The encryption works perfectly, i thought i would be able to copy the code and do the opposite to decrypt the message, however i receive the error:
letter = encryptionCharacters[temp_k]
"TypeError: String indices must be integers"
Not sure if anyone can fix this issue to be able to decrypt a message, but hopefully someone can give me some help.
Steps to use the program:
Select option 1 by entering that number from the menu.
Enter 854417 as the number
Then press 2 and choose a message to encrypt / decrypt.
from itertools import cycle
listOfDigits = []
listOfIllegalCharacters = []
encryptionCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz .'
encryptedMessageLettersPosition = []
decryptedMessageLettersPosition =[]
encryptedMessageList = []
def main(): #This Function is the base of the main menu
print()
print("********* Welcome to the Encryption Program *********")
print()
while True: #Start of while loop to get the users choice.
try: #Start of try method.
choice = int(input("""
1: Set Person Number
2. Encrypt a Message
3. Decrypt a Message
4. Quit
Please Choose an Option (1 - 4): """)) #Interactive menu itself taking in the users option as an integer.
except ValueError: #End of try method, in order to catch the possible value error of entering a string instead of an integer.
print("!!!!!!ERROR!!!!!!")
print()
print("ERROR: Choice was not valid!")
print("Try Again")
print()
print("!!!!!!ERROR!!!!!!")
main() #Call to menu method (a.k.a restart).
if choice == 1:
personNumberInput() #Call to personNumberInput method, which allows the user to enter their personal ID number for the encryption.
elif choice == 2:
if len(listOfDigits) == 0:
print()
print("!!!!!!ERROR!!!!!!")
print()
print("You have not set a Person Number")
print("Please Select Option 1 and set a Person Number to begin Encryption / Decryption")
print()
print("!!!!!!ERROR!!!!!!")
else:
messageEncrypt()
elif choice == 3:
if len(listOfDigits) == 0:
print()
print("!!!!!!ERROR!!!!!!")
print()
print("You have not set a Person Number")
print("Please Select Option 1 and set a Person Number to begin Encryption / Decryption")
print()
print("!!!!!!ERROR!!!!!!")
else:
messageDecrypt()
elif choice == 4:
menuQuit()
else:
print()
print("!!!!!!ERROR!!!!!!") #If none of the options are chosen, restart and provide a suitable error message.
print()
print("You must only select 1, 2, 3 or 4.")
print("Please Try Again")
print()
print("!!!!!!ERROR!!!!!!")
main()
def menuQuit(): #This function is the 4th option on the menu.
print()
userOption = input("Are you sure you want to Quit / Exit the Program? (Y/N): ") #Taking the users input to get their decision.
if userOption == "y":
exit()
elif userOption == "Y":
exit() #Exit the program if the user confirms their choice with "y" or "Y".
else:
print()
print("You have been returned to the Main Menu")
main() #Returning the user to the menu for any other option including "n" or "N".
def personNumberInput():
while True:
try:
print()
personNumber = int(input("Please enter your Person Number: ")) #Checking the input from the user.
except ValueError: #Catching the value error of unexpected value (non integer).
print()
print("ERROR: Person Number contained a non integer, Try Again")
continue
else:
personNumberInt = len(str(abs(personNumber))) #Getting the length of the string as well as the absolute value of each digit entered.
break
while True:
if (personNumberInt) != 6: #If the length of the number entered is not 6, try again.
print()
print("ERROR: Person Number length not equal to 6, Try Again")
return personNumberInput()
else:
print()
print ("The Person Number you have entered is:", personNumber)
print ("Ready to Encrypt / Decrypt a Message")
personNumberDigits = [int(x) for x in str(personNumber)]
listOfDigits.extend(personNumberDigits)
break
def messageEncrypt():
print()
message = input("Please Enter a Message to Encrypt: ")
messageLetters = []
messageLettersPosition = []
for char in message:
messageLetters += char
for i in messageLetters:
position = encryptionCharacters.find(i)
position = position + 1
messageLettersPosition.append(position)
digits = messageLettersPosition
values = cycle(listOfDigits)
for j, (digit, value) in enumerate(zip(digits, values)):
if j % 2 == 0:
val = digit - value-1
encryptedMessageLettersPosition.append(val)
elif j % 3 == 1:
val = digit - value*3-1
encryptedMessageLettersPosition.append(val)
else:
val = digit + value-1
encryptedMessageLettersPosition.append(val)
for k in encryptedMessageLettersPosition:
temp_k = k % len(encryptionCharacters)
letter = encryptionCharacters[temp_k]
encryptedMessageList.append(letter)
print()
print ("Your message has been Encrypted!")
print ("Encrypted Message Output:",(''.join(encryptedMessageList)))
encryptedMessageLettersPosition.clear()
encryptedMessageList.clear()
def messageDecrypt():
print()
message = input("Please Enter a Message to Decrypt: ")
messageLetters = []
messageLettersPosition = []
for char in message:
messageLetters += char
for i in messageLetters:
position = encryptionCharacters.find(i)
position = position + 1
messageLettersPosition.append(position)
digits = messageLettersPosition
values = cycle(listOfDigits)
for j, (digit, value) in enumerate(zip(digits, values)):
if j % 2 == 0:
val = digit + value-1
encryptedMessageLettersPosition.append(val)
elif j % 3 == 1:
val = digit + value/3-1
encryptedMessageLettersPosition.append(val)
else:
val = digit - value-1
encryptedMessageLettersPosition.append(val)
for k in encryptedMessageLettersPosition:
temp_k = k % len(encryptionCharacters)
letter = encryptionCharacters[temp_k]
encryptedMessageList.append(letter)
main()
Try making temp_k an integer using int()
temp_k = int( k % len(encryptionCharacters) )
letter = encryptionCharacters[temp_k]
Some of the values in encryptedMessageLettersPosition are floats, not integers.
Therefore temp_k = k % len(encryptionCharacters) sometimes returns a float value, and you cannot use a float as a string index.
I'm trying to create an encryption program that is also capable of using a username and password to be accessed, alongside the password being able to be changed, however, I am getting the following error when trying to read the password from a file.
Traceback (most recent call last):
File "C:/Users/Matthew/AppData/Local/Programs/Python/Python37-32/a.py", line 28, in <module>
password()
File "C:/Users/Matthew/AppData/Local/Programs/Python/Python37-32/a.py", line 9, in password
var2 = open("Users\Matthew\AppData\Local\Programs\Python\Python37-32\password.txt","r")
FileNotFoundError: [Errno 2] No such file or directory: 'Users\\Matthew\\AppData\\Local\\Programs\\Python\\Python37-32\\password.txt'
Password is saved in the Users\Matthew\AppData\Local\Programs\Python\Python37-32\password.txt directory.
Below is the code.
import os
import time
def password():
while True:
username = input ("Enter Username: ")
password = input ("Enter Password: ")
var1 = "admin"
var2 = open("Users\Matthew\AppData\Local\Programs\Python\Python37-32\password.txt","r")
if username == var1 and password == var2:
time.sleep(1)
print ("Login successful!")
answer = input("Do you wish to change your password (Y/N): ")
if input == "Y" or "y":
var2 = input("Enter new password: ")
elif input == "N" or "n":
break
logged()
break
else:
print ("Password did not match!")
def logged():
time.sleep(1)
print ("Welcome to the encryption program.")
password()
def main():
result = 'Your message is: '
message = ''
choice = 'none'
while choice != '-1':
choice = input("\nDo you want to encrypt or decrypt the message?\nEnter 1 to Encrypt, 2 to Decrypt, -1 to Exit Program: ")
if choice == '1':
message = input("\nEnter the message to encrypt: ")
for i in range(0, len(message)):
result = result + chr(ord(message[i]) - 2)
print (result + '\n\n')
result = ''
elif choice == '2':
message = input("\nEnter the message to decrypt: ")
for i in range(0, len(message)):
result = result + chr(ord(message[i]) + 2)
print (result + '\n\n')
result = ''
elif choice != '-1':
print ("You have entered an invalid choice. Please try again.\n\n")
elif choice == '-1':
exit()
main()
Any help is appreciated, thanks!
Provide the complete path:
var2 = open("C:/Users/Matthew/AppData/Local/Programs/Python/Python37-32/password.txt","r")
Edit:
As you said in the comment that it worked but the password was marked as incorrect, so I have fixed issues with your code.
You cannot read data directly by opening a file. You will have to use the command read to get the data:
file = open("C:/Users/Matthew/AppData/Local/Programs/Python/Python36/password.txt","r")
var2 = file.read()
file.close()
Your second code problem is setting new password. The code you made:
answer = input("Do you wish to change your password (Y/N): ")
if input == "Y" or "y":
var2 = input("Enter new password: ")
elif input == "N" or "n":
break
Don't use input to see the value, use the variable in which you stored the input data. Also lower the string to make it easy:
answer = input("Do you wish to change your password (Y/N): ")
if answer.lower() == "y":
var2 = input("Enter new password: ")
elif answer.lower() == "n":
break
The full code can be like:
import os
import time
def password():
while True:
username = input ("Enter Username: ")
password = input ("Enter Password: ")
var1 = "admin"
file = open("C:/Users/Matthew/AppData/Local/Programs/Python/Python36/password.txt","r")
var2 = file.read()
file.close()
if username == var1 and password == var2:
time.sleep(1)
print ("Login successful!")
answer = input("Do you wish to change your password (Y/N): ")
if answer.lower() == "y":
var2 = input("Enter new password: ")
elif answer.lower() == "n":
break
logged()
break
else:
print ("Incorrect Information!")
def logged():
time.sleep(1)
print ("Welcome to the Encryption program.")
password()
def main():
result = 'Your message is: '
message = ''
choice = 'none'
while choice != '-1':
choice = input("\nDo you want to encrypt or decrypt the message?\nEnter 1 to Encrypt, 2 to Decrypt, -1 to Exit Program: ")
if choice == '1':
message = input("\nEnter the message to encrypt: ")
for i in range(0, len(message)):
result = result + chr(ord(message[i]) - 2)
print (result + '\n\n')
result = ''
elif choice == '2':
message = input("\nEnter the message to decrypt: ")
for i in range(0, len(message)):
result = result + chr(ord(message[i]) + 2)
print (result + '\n\n')
result = ''
elif choice != '-1':
print ("You have entered an invalid choice. Please try again.\n\n")
elif choice == '-1':
exit()
main()
I need my 'items' variable to print each item on a new line. I keep getting a total in 'items' and the total in 'total'. The 'total' prints out how I want, but I want the items to print individually.
Thoughts?
def adding_report():
user_input = input("Report Types include All Items ('A') or Total Only ('T')\nChoose Report Type ('A'or'T'):")
items = "\n"
total = 0
while True:
if user_input == 'A'.lower():
user_input1 = input("Input an integer to add to the total or 'Q' to quit: ")
if user_input1.isdigit():
items = int(user_input1)
total += int(user_input1)
continue
elif user_input1 == 'Q'.lower():
print("Items\n", items)
print("Total\n", total)
break
elif user_input1.startswith('q'):
print('Items\n', int(items))
print("Total\n", total)
break
else:
print("Input is not valid")
elif user_input == 'T'.lower():
user_input2 = input("Input an integer to add the total or 'Q' to quit: ")
adding_report()
user_input = raw_input("Report Types include All Items ('A') or Total Only ('T')\nChoose Report Type ('A'or'T'):")
items=[]
total = 0
print user_input
total = 0
while True:
user_input1 = raw_input("Input an integer to add to the total or 'Q' to quit: ")
if user_input == 'A'.lower() or user_input == "A":
if user_input1.isdigit():
items.append(int(user_input1))
total += int(user_input1)
continue
elif user_input1 == 'Q'.lower() or user_input1 =="Q" or user_input1.startswith('q'):
print "List of items is"
for item in items:
print item
print "Total ", total
break
else:
print("Input is not valid")
elif user_input == 'T'.lower() or user_input == "T":
if user_input1.isdigit():
items.append(int(user_input1))
total += int(user_input1)
continue
elif user_input1 == 'Q'.lower() or user_input1 =="Q" or user_input1.startswith('q'):
print "Total ",total
break
else:
print("Input is not valid")
Here is a modified code. It is hard to exactly understand what your script is supposed to do:
import textwrap # nice library to format text inside functions
def adding_report():
# initiate variables
total = 0
items = 0
# Make sure you get the right input
while True:
user_input = input(textwrap.dedent("""\
Report Types include All Items ('A') or Total Only ('T')
Choose Report Type ('A'or'T'):"""))
if user_input list("AT"):
break
# Create a loop where you ask the user for input
# Q or q quits (the print is outside the function)
while True:
user_input1 = input("Input an integer to add to the total or 'Q' to quit: ")
if user_input1.lower() == 'q':
break
if user_input1.isdigit():
if user_input == 'A':
items = int(user_input1)
total += int(user_input1)
elif user_input == 'T':
total += int(user_input1)
else:
print("Input is not valid")
# Return variables
return items,total
items,total = adding_report()
print("Items\n", items)
print("Total\n", total)
Here's my attempt at understanding what you trying to do:
print("Report Types includes All Items ('A') or Total Only ('T')")
report_type_raw = input("Choose Report Type ('A' or 'T'): ")
report_type = report_type_raw.lower()
if report_type in 'at':
items = []
total = 0
user_input = ''
while user_input != 'q':
user_input_raw = input("Input an integer to add to the total or 'Q' to quit: ")
if user_input_raw.isdigit():
current_item = int(user_input_raw)
if report_type == 'a':
items.append(user_input_raw)
total += current_item
user_input = ''
else:
user_input = user_input_raw.lower()
if user_input != 'q':
print("Input is not valid")
if report_type == 'a':
how_items_to_be_printed = ', '.join(items)
print("Items :", how_items_to_be_printed)
print("Total :", total)
else:
print("Report type is not valid")
Otherwise you'll have to clarify what you were trying to do.
I began this code by using a while loop to establish the menu (line 19-40) and it worked perfectly before adding the functions and import at the top. Now it keeps throwing back an indentation error at line 19 and none of my attempts other than removing all the functions seem to fix this problem. Any chance I overlooked something?
import string
def encrypt(input_val):
en_key = input("Enter the number to shift by:")
var = to_encrypt.upper()
for char in var:
shift = ord(char) + en_key
encrypted += chr(shift)
return encrypted.upper()
def decrypt(input_val):
de_key = input("Enter the number to shift by:")
var = to_decrypt.upper()
for char in var:
shift = ord(char) - de_key
decrypted += chr(shift)
return decrypted.upper()
def crack(input_val):
program_on = True
while program_on == True:
print("Please select from the following options:\n \t1. Encrypt A Message\n \t2. Decrypt A Message\n \t3. Attempt To Crack A Message\n \t4. Quit")
user_choice = input("Enter Your Choice: ")
if user_choice == "1":
to_encrypt = input("Enter message to encrypt:")
encrypt(to_encrypt)
program_on = True
elif user_choice == "2":
to_decrypt = input("Enter encrypted message:")
decrypt(to_decrypt)
program_on = True
elif user_choice == "3":
to_crack = input("Enter encrypted message:")
crack(to_crack)
program_on = True
elif user_choice == "4":
print("Goodbye")
program_on = False
else:
print("Give a valid response")
program_on = True
Seems to work now.
def crack(input_val):
pass
You can't define an empty function.