0

だから私は暗号用のPythonプログラムを作成しようとしていて、(2つの異なる暗号を結合して)作成しました。プログラムを毎回開いたり閉じたりせずに、異なる文字列を簡単に暗号化できるようにしようとして立ち往生しています。64ビットのWindows7コンピューターでPython3.2を使用しています。

これが私のコードです(少し磨くためのヒントも教えてください):

#!/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()
4

1 に答える 1

6

優れたプログラミング手法は、コードをモジュール化された機能単位に分割することです。たとえば、実際に暗号化を行う1 つの関数、ユーザー入力を収集する 1 つの関数などです。このアイデアのより高度でモジュール化されたバージョンは、オブジェクト指向プログラミングです。今日、ほとんどの大規模なプロジェクトやプログラミング言語で使用されています。(興味がある場合は、このチュートリアルのように、OOP を学ぶための優れたリソースがたくさんあります。)

最も簡単に言えば、暗号自体を独自の関数に入れ、ユーザーがメッセージを入力するたびにそれを呼び出すことができます。これはトリックを行います:

#!/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")

このプログラムは、ユーザーに別のメッセージを要求している間、永久にループします。キーの組み合わせctrl+を使用しcてプログラムを停止します。

于 2012-09-23T04:21:08.510 に答える