2015-06-28 94 views
0
phrase = input("Enter text to Cipher: ") 
shift = int(input("Please enter shift: ")) 
encryption = input("Do you want to [E]ncrypt or [D]ecrypt?: ").upper 

new_strs = [] 

for character in phrase: 
    x = ord(character) 
    if encryption == ("E"): 
     new = x + shift 
    if encryption == ("D"): 
     new = x - shift 

new_strs.append(chr(new)) 

print (("").join(new_strs)) 

代碼有效,只要我沒有「if encryption = E/D」但它不會如果我這樣做。變量'new'沒有定義

這是發生的錯誤消息。

Traceback (most recent call last): 
File "C:\Python34\Doc\test.py", line 14, in <module> 
    new_strs.append(chr(new)) 
NameError: name 'new' is not defined 
+1

嘗試更改爲'upper()'而不是'upper'。這是一個功能。 – mehtunguh

回答

0

您需要在for循環內包含new_strs.append(chr(new))。而且你還需要在for循環中聲明該變量。這都是關於變量的範圍。如果你把new_strs.append(chr(new))放在for循環之外,Python會在for循環之外尋找一個變量new,因爲你只在for循環中爲new變量賦值。

而你又必須爲空字符串分配給其內部存在的for循環,使new目前if條件內的值將被分配到其中存在的if外,但裏面的for變量newnew變量。

for character in phrase: 
    x = ord(character) 
    new = 0 
    if encryption == ("E"): 
     new = x + shift 
    if encryption == ("D"): 
     new = x - shift 

    new_strs.append(chr(new)) 
+0

這是一個很好的修正,但它不能解釋錯誤。 – mehtunguh

+0

認爲我完成了... –

+0

我似乎無法解決這個新的錯誤,它不幸發生它說「文件」C:\ Python34 \ Doc \ test.py「,第15行,在 new_strs.append(chr(新建)) TypeError:需要一個整數(得到的類型爲str)「 – MasterPayne3

1

您遇到的問題是new永遠不會被分配。這是因爲encryption == "E"是假的,所以encription == "F"也是。這是錯誤的原因是加密是一個功能!嘗試打印出來,你會看到。它是<function upper>。比較這兩條線

encryption = input("Do you want to [E]ncrypt or [D]ecrypt?: ").upper 
encryption = input("Do you want to [E]ncrypt or [D]ecrypt?: ").upper() 

第二個是正確的。這是你問題的根源。

還有其他問題,正如其他答案指出的那樣。在這裏合併它們,並且爲加密添加有效性檢查,這是我完整的解決方案。

phrase = input("Enter text to Cipher: ") 
shift = int(input("Please enter shift: ")) 
encryption = input("Do you want to [E]ncrypt or [D]ecrypt?: ").upper() 
if encryption not in ("E", "F"): 
    raise ValueError("invalid encryption type: %r" % encryption) 

new_strs = [] 

for character in phrase: 
    x = ord(character) 
    if encryption == "E": 
     new = x + shift 
    if encryption == "D": 
     new = x - shift 

    new_strs.append(chr(new)) 

print (("").join(new_strs))