python中的凯撒密码 [英] Caesar Cipher in python
本文介绍了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))
推荐答案
问题在这里:
print('Do you wish to encrypt or decrypt a message?')
mode = input().lower()
在Python 2.x输入中,使用raw_input()
代替input()
.
In Python 2.x input use raw_input()
instead of input()
.
Python 2.x:
Python 2.x:
- 从标准输入中读取字符串:
raw_input()
- 从标准输入中读取一个字符串,然后对其进行评估:
input()
.
- Read a string from standard input:
raw_input()
- Read a string from standard input and then evaluate it:
input()
.
Python 3.x:
Python 3.x:
- 从标准输入中读取字符串:
input()
- 从标准输入中读取一个字符串,然后对其进行评估:
eval(input())
.
- Read a string from standard input:
input()
- Read a string from standard input and then evaluate it:
eval(input())
.
这篇关于python中的凯撒密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文