2013-07-13 86 views
0

我一直工作在Python中一个简单的凯撒移位,但是当我尝试运行它,它说:追加海峡到海峡

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() 

回答

1

的问题是,你定义你的函数shift和你的字符串变量shift

一个快速解决方法是重命名您的函数和变量,以便不存在冲突。

+0

等等,不要错过。非常感谢您的观察!我想我缺乏睡眠 – Clement

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 
>>>