变量new未定义

2024-04-26 12:14:38 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: to代码textinnewinputifshift
2条回答

您需要在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。你知道吗

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

您遇到的问题是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))

相关问题 更多 >