2015-02-12 19 views
-3
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變量是未定義的。我以爲我已經在上面的代碼中定義了它,但顯然不是。我錯過了什麼?ceaser密碼中未定義的變量-Python

+0

你'高清的main():'在while循環?另請確定遊覽縮進。 – Marcin 2015-02-12 02:09:25

+0

我會修正縮進,但我仍然不知道爲什麼cryptMessage是未定義的。我以前只運行過加密部分,並沒有得到那個錯誤。 – 2015-02-12 02:23:15

+1

這裏沒有正確的縮進,它很難理解你的程序應該如何表現。在Python中,縮進對正確執行至關重要。沒有這個,它很難在代碼spinet中看到任何結構/邏輯。 – Marcin 2015-02-12 02:26:17

回答

0

我重新編寫了一段代碼。你得到一個未定義的變量錯誤的原因是因爲你在你的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 (
+0

哇,謝謝你!有沒有辦法讓原始數組顯示明文結果,然後顯示除了明文結果之外的編碼消息? – 2015-02-12 03:32:24

+0

您可以只用另一個單獨的數組來存儲所有原始文本。基本上和你現在擁有的'array'一樣,但是在循環中'append(input)'而不是'append(cryptMessage)' – Tyler 2015-02-12 03:35:27

+0

有沒有什麼辦法可以在打印array? – 2015-02-12 21:46:13