【问题标题】:Encryption program - i don't get why it throws these errors加密程序 - 我不明白为什么它会抛出这些错误
【发布时间】: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


【解决方案1】:

for 调用不应该是

for i in range(len(word))

?

len 只返回数字单词的长度

【讨论】:

    猜你喜欢
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2023-04-10
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多