[Tutor] I am trying to get my encryption program to print from my def main. I am just learning the program.
Alan Gauld
alan.gauld at btinternet.com
Fri May 1 14:45:47 CEST 2015
On 01/05/15 11:48, Corneil Lionel wrote:
> text_list=[]
> temp=[]
> import allison
> import corneil
> def main():
> choice=input("Would you like to begin? y/n: ")
> while choice!='n':
> d=cipher()
>
> alphabet=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
> print('Would you like to encrypt or decrypt your text?')
Notice that the alphabet line is not indented to the rest of main.
Python will take that as the end of main() and thus your main just loops
around doing the cipher() it never reaches the alphabet line.
However I would expect python to try to execute this code and
see the wrong indentation.
Do you get an indent error when you run it?
Or is it just an email formatting error?
> choice=input('Enter "e" to encrypt or "d" to decrypt: ')
> while choice!="d" and choice!="e":
> print("That is not a valid option, please choose again.")
> choice=input('Enter "e" to encrypt or "d" to decrypt: ')
> if choice=="e":
> text=intro("plain")
> corneil.encrypt(text,d,alphabet)
> else:
> text=intro("encrypted")
> #print(text)
> allison.decrypt(text,d,alphabet)
> print()
> choice=input("Would you like to go again? y/n: ")
>
> def cipher():
> d={}
> temp=[]
> try:
> f=open('cipher.txt','r')
> for x in f:
> temp=x.rstrip().split(':')
> d[temp[0]]=temp[1]
> except Exception as err:
> print(err)
You should catch specific exceptions. This could mask real
errors. Especially since you just print a message which
Python does for you anyway...
> return d
>
> def intro(x):
> print('Please enter your',x,'text. Type "quit" to quit.')
> text=input("")
> y=""
> while text!="quit":
> y+=text.upper()
> #text_list.append(text)
> text=input()
> return y
>
> main()
> AND THIS IS NOT PRINTING OUT WHEN I TRY TO ENCODE
>
> def encrypt(text,cipher,a):
> encrypted=""
> for char in text:
> if char in cipher:
You have defined cipher to be a function above.
You cannot iterate over a function object.
cipher() returns a dictionary, did you perhaps
intend to call cipher?
if char in cipher():
> encrypted+=cipher[char.upper()]
Again cipher is a function. You probably intended to
call cipher here:
encrypted+=cipher()[char.upper()]
However since you are accessing the same dict twice you
should probably just call cipher once and store the result:
cipher_dict = cipher()
if char in cipher_dict:
encrypter += cipher_dict[char.upper()]
> else:
> encrypted+=char
>
> return encrypted
> print(encrypted)
Once the return executes you are out of the function so
the final print() never executes.
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list