2013-07-13 84 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 
>>>