0

我一直在用 python 做一个简单的 Caesar Shift,但是当我尝试运行它时,它说:

File "Ceaser Shift.py", line 36, in main
ciphertext += shift(letter,shift)
TypeError: 'str' object is not callable

我试图弄清楚它为什么这样做,并且我可以在正常的 IDLE 环境中添加到字符串中,并且没有看到任何在线相关的内容,因为我没有在脚本中的任何地方重新定义 str 。任何帮助都会很棒!

我的代码:

## Doesn't support changing shifts during computation, to do this either the database must be re-written or script restarted

import time, os, string

global selmemo
shiftmemo = {}

def shift(l,shift):
    if l not in shiftmemo:
        charset = list(string.ascii_lowercase)
        place = charset.index(l.lower())
        shiftplace = charset.index(shift.lower())

        shiftmemo[l] = charset[(place+shiftplace)%25]

    return shiftmemo[l]

def main():
    shift = None
    ciphertext = ""

    print("--- Welcome ---")
    print("--- Ceaser Shifter ---")
    print("Commands: shift, encrypt, clear, print, quit")
    choice = input(": ")

    while choice != "quit":
        if choice == "shift":
            shift = input("Please enter a shift letter: ")

        elif choice == "encrypt" and shift != None:
            uparse = input("Enter your plaintext: ")
            for letter in uparse:
                if letter.lower() in string.ascii_lowercase:
                    ciphertext += shift(letter,shift)
                else:
                    ciphertext += letter

        elif choice == "clear":
            shift = ""
            ciphertext = ""
            shiftmemo = {}

        elif choice == "print":
            print(ciphertext)

        else:
            pass

        choice = input(": ")

main()
4

2 回答 2

1

问题是您定义了函数shift和字符串变量shift

一个快速的解决方法是重命名您的函数和变量,以免发生冲突。

于 2013-07-13T01:12:22.873 回答
0

shift只是名字。解释器将名称的值识别为用户定义的函数。因此,您可以通过将值分配给另一个名称来使用这样的函数:

>>> def func():
...     print('a')
... 
>>> f = func
>>> f()
a
>>> 

但是,如果您为名称分配一个新值,它可能不再是一个函数。

>>> func = None
>>> type(func)
<class 'NoneType'>
>>> func()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
>>> 
于 2013-07-13T01:24:34.010 回答