Python: 凯撒密码加密
大家好,我有个问题。为什么下面的代码既没有输出也没有错误呢?
这段代码是用来加密和解密用户代码的。
alpha = ['a','b','c','d','e','f',
'g','h','i','j','k','l',
'm','n','o','p','q','r',
's','t','u','v','w','x',
'y','z']
shift = range(26)
def user_info():
info = input("\nPress 'e' to encrypt or 'd' to decrypt: ").lower()
if info == 'e' or 'd':
return info
def user_message():
code = input("What is your message?: ")
return code
def user_shift():
shift = int(input("What is your shift number?: "))
while True:
if shift == int(shift):
return shift
def True_Message(info, code, shift):
if info[0] == 'd': #This encrypts the code
shift = -shift
for letter in code:
if letter in alpha:
alpha_2 = ord(letter) + shift
secret_message = ""
if alpha_2 in range (0, len(alpha)):
final_mix = chr(alpha)
secret_message += final_mix
return secret_message
info = user_info()
code = user_message()
shift = user_shift()
print(True_Message(info, code, shift))
没有任何错误,所以我不知道哪里出了问题。我对加密这块还很陌生,不确定这是否是正确的方向,有什么想法吗?谢谢。
更新!!!!!
抱歉,我希望这段代码能够根据用户的选择来加密和解密代码。
4 个回答
1
正如其他人所说,你有一些缩进的问题。
从逻辑上讲,你应该确认一下 secret_message = ""
这是否是你想要的结果。
还有几点需要注意:
- 如果
letter
是Z
,然后你再加一个偏移量,会发生什么?(查看ASCII表) - 你确定一开始就想让偏移量是
range(26)
吗?试试print(list(range(26)))
来看看这个范围到底是什么样的。
别气馁,玩ASCII一开始可能会让人感到沮丧,但一旦熟悉了,就会变得非常有趣!
1
Python是一种对缩进很敏感的编程语言。你的代码里到处都是缩进错误。
你怎么能说“没有错误”呢?你有在运行这个脚本吗?Python解释器会准确告诉你错误在哪里。当我运行你的脚本时:
C:\Users\Jonathon\temp>python caesar.py
File "caesar.py", line 22
return shift
^
IndentationError: expected an indented block
所以你的第一个错误在这里:
def user_shift():
shift = int(input("What is your shift number?: "))
while True:
if shift == int(shift):
return shift # ---> Should be indented one more level
3
你需要检查一下你的缩进和使用的 or
运算符:
alpha = ['a','b','c','d','e','f',
'g','h','i','j','k','l',
'm','n','o','p','q','r',
's','t','u','v','w','x',
'y','z']
shift = range(26)
def user_info():
info = input("\nPress 'e' to encrypt or 'd' to decrypt: ").lower()
if info in ('e', 'd'): # 'or' does not work how you think it does
return info
def user_message():
code = input("What is your message?: ")
return code
def user_shift():
while True:
shift = int(input("What is your shift number?: "))
if shift == int(shift):
return shift
def True_Message(info, code, shift):
if info[0] == 'd': #This encrypts the code
shift = -shift
for letter in code:
if letter in alpha:
alpha_2 = ord(letter) + shift
secret_message = ""
if alpha_2 in range (0, len(alpha)):
final_mix = chr(alpha)
secret_message += final_mix
return secret_message