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”时,代码就可以工作,但是如果我这样做了,代码就不能工作。你知道吗
这是正在发生的错误消息。你知道吗
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
您需要在
for
循环中包含new_strs.append(chr(new))
。你还需要在for循环中声明这个变量。这都是关于变量范围的。如果将new_strs.append(chr(new))
放在for循环外,python将在for循环外寻找变量new
,因为只在for循环内为new
变量赋值。你知道吗同样,您必须将一个空字符串赋给存在于for循环中的
new
变量,这样在if
条件中存在的new
的值将被赋给存在于if
外部但在for
内部的变量new
。你知道吗您遇到的问题是
new
从未被分配。这是因为encryption == "E"
是假的,encription == "F"
也是假的。错误的原因是加密是一个函数!试着把它打印出来,你会看到的。它是<function upper>
。比较这两条线第二个是正确的。这就是你问题的根源。你知道吗
正如其他答案所指出的,还有其他问题。将它们结合在一起,并添加加密的有效性检查,这是我的完整解决方案。你知道吗
相关问题 更多 >
编程相关推荐