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))
只要我没有&#34,代码就可以工作;如果加密= 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
答案 0 :(得分: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))
答案 1 :(得分:0)
您需要在new_strs.append(chr(new))
循环中包含for
。而且你还需要在for循环中声明该变量。这完全取决于变量范围。如果你把new_strs.append(chr(new))
放在for循环之外,python会在for循环之外寻找一个变量new
,因为你只需要在for new
变量中为new
变量赋值。循环。
同样,您必须将一个空字符串分配给存在于for循环中的new
变量,以便将if
条件中存在的new
值分配给变量if
存在于for
之外但位于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))
内。
$file = file_get_contents("text.txt");
// This explodes on new line
// As suggested by @Dagon, use of the constant PHP_EOL
// is a better option than \n for it's universality
$value = explode(PHP_EOL,$file);
// filter empty values
$array = array_filter($value);
// This splits the array into chunks of 3 key/value pairs
$array = array_chunk($array,3);