如何在python中循环回我的程序的一部分?

col*_*000 0 python loops

所以我一直在尝试为我的firend做一个python程序,我做了(加入了两个不同的密码),并且我一直试图让每次打开和关闭程序时都很容易加密不同的字符串.我在64位Windows 7计算机上使用python 3.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()
Run Code Online (Sandbox Code Playgroud)

Pet*_*bot 6

良好的编程习惯是将代码分解为模块化的功能单元 - 例如,一个实际执行密码的函数,一个收集用户输入的函数,等等.这个想法的更高级和更模块化的版本是面向对象的编程 -今天用于大多数大型项目和编程语言.(如果您有兴趣,有很多很好的资源可以学习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")
Run Code Online (Sandbox Code Playgroud)

此程序现在将永远循环,同时向用户询问另一条消息 - 使用组合键ctrl+ c来停止程序.