2010-10-07 159 views
1

我正的錯誤是凱撒密碼在python

Traceback (most recent call last): 
    File "imp.py", line 52, in <module> 
    mode = getMode() 
    File "imp.py", line 8, in getMode 
    mode = input().lower() 
    File "<string>", line 1, in <module> 
NameError: name 'encrypt' is not defined 

下面是代碼。

# Caesar Cipher 


MAX_KEY_SIZE = 26 

def getMode(): 
    while True: 
     print('Do you wish to encrypt or decrypt a message?') 
     mode = input().lower() 
     if mode in 'encrypt e decrypt d'.split(): 
      return mode 
     else: 
      print('Enter either "encrypt" or "e" or "decrypt" or "d".') 

def getMessage(): 
    print('Enter your message:') 
    return input() 

def getKey(): 
    key = 0 
    while True: 
     print('Enter the key number (1-%s)' % (MAX_KEY_SIZE)) 
     key = int(input()) 
     if (key >= 1 and key <= MAX_KEY_SIZE): 
      return key 

def getTranslatedMessage(mode, message, key): 
    if mode[0] == 'd': 
     key = -key 
    translated = '' 

    for symbol in message: 
     if symbol.isalpha(): 
      num = ord(symbol) 
      num += key 

      if symbol.isupper(): 
       if num > ord('Z'): 
        num -= 26 
       elif num < ord('A'): 
        num += 26 
      elif symbol.islower(): 
       if num > ord('z'): 
        num -= 26 
       elif num < ord('a'): 
        num += 26 

      translated += chr(num) 
     else: 
      translated += symbol 
    return translated 

mode = getMode() 
message = getMessage() 
key = getKey() 

print('Your translated text is:') 
print(getTranslatedMessage(mode, message, key)) 
+1

這與您所看到的錯誤無關,但您可能需要查看'string.translate()'http://docs.python.org/library/stdtypes.html#str.translate – 2010-10-07 15:38:55

回答

7

的問題是在這裏:

print('Do you wish to encrypt or decrypt a message?') 
mode = input().lower() 

在Python 2.x中輸入使用raw_input()代替input()

的Python 2.x的:

  • 閱讀從標準輸入的字符串:raw_input()
  • 閱讀從標準輸入一個字符串,然後評估它:input()

Python 3.x都有:

  • 閱讀從標準輸入的字符串:input()
  • 閱讀從標準輸入一個字符串,然後評估它:eval(input())
2

input()評估您輸入的表達式。改爲使用raw_input()

+0

它的工作......讓你有這麼多的幫助... – Abhijit 2010-10-07 15:16:35