caesar密码-Python中的未定义变量

时间:2015-02-12 02:06:56

标签: python variables encryption undefined

 import sys
 import string

 array = []

while True:

input = raw_input("Please enter no more than 10 characters, one per line, and terminate the message by entering % ")

def main():
     key = 3
     message = input
     cryptMessage = ""
     for ch in message:
           cryptMessage = cryptMessage + chr(ord(ch) + key)

if input == "%"

print array, len(array), "The coded message is:", cryptMessage 
sys.exit(1) #This tells the program to exit
array.append(input)
main()

除了以加密形式打印用户输入文本之外,我基本上都按照我想要的方式工作。它已经以常规形式打印,我希望它以常规和加密形式打印。它一直说打印行中的cryptMessage变量是未定义的。我以为我已经在上面的代码中定义了它,但显然没有。我错过了什么?

1 个答案:

答案 0 :(得分:0)

我重新编写了一些代码。您收到未定义变量错误的原因是因为您在cryptMessage函数中定义了main(),并且在此之外无法访问它。

import sys

# these can be declared up here
array = []
key = 3

# loop until the user tells us not to
while True:

     # grab the input from the user
    input = raw_input("Please enter no more than 10 characters, one per line, and terminate the message by entering % ")

    # the string we'll fill
    cryptMessage = ""

    # go over the input and 'cypher' it
    for ch in input:
        cryptMessage += chr(ord(ch) + key)

    # add this line of message to the array
    array.append(cryptMessage)

    # when the user tells us to stop
    if input == "%":

        # print and break out of the while loop
        print "The coded message is:", ' '.join(array)
        break

输出:

Please enter no more than 10 characters, one per line, and terminate the message by entering % tyler
Please enter no more than 10 characters, one per line, and terminate the message by entering % is 
Please enter no more than 10 characters, one per line, and terminate the message by entering % my
Please enter no more than 10 characters, one per line, and terminate the message by entering % name
Please enter no more than 10 characters, one per line, and terminate the message by entering % %
The coded message is: w|ohu lv# p| qdph (