【发布时间】:2018-04-06 07:25:25
【问题描述】:
我正在用python创建一个加密程序,使用简单的密码,反转字符串并在字母表中向前移动3个字母。
original = input('Enter a phrase: ')
actual_word = original[::-1]
def mid(s, offset, amount):
return s[offset:offset+amount]
def encrypt(word):
for i in len(word):
newtxt = mid(word, i, 1)
newtxt = chr(ord(newtxt)+3)
coded = coded + newtxt
return coded
encrypted = encrypt(original)
print(encrypted)
input('Press ENTER to exit')
但是我收到了这些错误,但我不明白为什么会收到这些错误:
Traceback (most recent call last):
File "C:\Users\MHT\Desktop\Python\Kryptering\Encryption.py", line 14, in <module>
encrypted = encrypt(original)
File "C:\Users\MHT\Desktop\Python\Kryptering\Encryption.py", line 8, in encrypt
for i in len(word):
TypeError: 'int' object is not iterable
【问题讨论】:
-
1不要大写。2你也应该用python 标记。 -
短:
def encrypt(word, shift=3): return ''.join(chr(ord(i)+shift) for i in word)。您也可以使用它来“解密”负移位 (-3)。但请注意,这不是加密,而是混淆(最多)。 -
关于错误,
len返回一个不可迭代的 int(请参阅下面的答案以获取解决方案)。然后,您必须通过定义coded来修复UnboundLocalError异常 - 或使用我之前评论中描述的较短版本。
标签: python python-3.x