ceaser密码Python中的未定义变量

2024-05-14 08:18:42 发布

您现在位置:Python中文网/ 问答频道 /正文

 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变量未定义。我以为我已经在上面的代码中定义了它,但显然不是。我错过了什么?你知道吗


Tags: thekeyimportmessageinputstringmain格式
1条回答
网友
1楼 · 发布于 2024-05-14 08:18:42

我重新编写了你的代码。出现未定义变量错误的原因是,您在main()函数中定义了cryptMessage,并且在该函数之外无法访问它。你知道吗

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 (

相关问题 更多 >

    热门问题