【问题标题】:Caesar Cipher in pythonpython中的凯撒密码
【发布时间】:2010-10-07 15:08:19
【问题描述】:

我得到的错误是

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))

【问题讨论】:

标签: python input python-2.x


【解决方案1】:

问题出在这里:

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()

    【讨论】:

      猜你喜欢
      • 2014-03-30
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 2018-12-28
      • 2015-01-08
      • 2012-06-03
      相关资源
      最近更新 更多