0

So I've been trying to make a python program for a cypher my firend and I did (joined 2 different cyphers) and I've been stuck trying to make it easy to encrypt different string without opening and closing the program every time. I'm using python 3.2 on a 64-bit windows 7 computer.

Here is my code (please also give me tips to polish it a bit):

#!/usr/bin/python

#from string import maketrans   # Required to call maketrans function.

print ("Welcome to the Rotten Bat encription program. Coded in python by Diego Granada")
answer = input("Please enter the password: ")
if answer == 'raindrops':
    print("Password accepted")
else:
    print ("Incorrect password. Quiting")
    from time import sleep
    sleep(3)
    exit()
intab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
outtab = "N9Q2T1VWXYZ7B3D5F8H4JK60n9pq2st1vwxyz7b3d5f8h4jk60"

message = input("Put your message here: ")

print(message.translate(dict((ord(x), y) for (x, y) in zip(intab, outtab))))

print ("Thank you for using this program")

input()
pablosaraiva
  • 2,343
  • 1
  • 27
  • 38

1 Answers1

6

Good programming practice is to break your code into modular units of functionality - for instance, one function that actually does the cipher, one function that gathers user input, etc. The more advanced and more modular version of this idea is Object-Oriented Programming - used in most large projects and programming languages today. (If you're interested, there are many great resources to learn OOP, like this tutorial.)

Most simply, you could put your cipher itself into its own function, then call it every time the user inputs a message. This would do the trick:

#!/usr/bin/python

print ("Welcome to the Rotten Bat encription program. Coded in python by Diego Granada")
answer = input("Please enter the password: ")
if answer == 'raindrops':
    print("Password accepted")
else:
    print ("Incorrect password. Quiting")
    from time import sleep
    sleep(3)
    exit()

def cipher(message):
    intab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    outtab = "N9Q2T1VWXYZ7B3D5F8H4JK60n9pq2st1vwxyz7b3d5f8h4jk60"
    return (message.translate(dict((ord(x), y) for (x, y) in zip(intab, outtab))))

while True:
    message = input("Put your message here: ")
    print cipher(message)
    print ("Thank you for using this program")

This program will now loop forever while asking the user for another message - use the key combination ctrl + c to stop the program.

Peter Sobot
  • 2,476
  • 21
  • 20
  • It's giving me a syntax error on line 20, highlighting cipher. – coldblade2000 Sep 24 '12 at 02:02
  • Be careful that you're not missing or adding any extra whitespace - Python uses it instead of braces and semicolons like other languages use. When I copy and paste the above sample into a file, it executes fine. Can you post the exact error? – Peter Sobot Sep 24 '12 at 03:39