首页 > 解决方案 > 几乎相同的功能,但不起作用?

问题描述

我使用 python 尝试了一些东西,虽然encrypt()函数工作正常,但decrypt()函数没有给我任何输出,甚至没有错误:(

我的代码:

import os
abc=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ', '.', ',', '1', '2', '3', '4',   '5', '6', '7', '8', '9', '0', '+', '-', ':', "'"]
mixed=abc[::-1]
os.system("clear")
def menu():
    print "-----------"
    print "[1] Encrypt"
    print "[2] Decrypt"
    print "-----------"
    if input(">>> ")==1:
        encrypt()
    elif input(">>> ")==2:
        decrypt()

def encrypt():
    os.system('clear')
    text=raw_input(">>> ").lower()
    text=list(text)
    textnew=text
    for i in range(len(text)):
        textnew[i]=mixed[abc.index(text[i])]
    print ''.join(textnew)
    menu()

def decrypt():
    os.system('clear')
    text=raw_input(">>> ").lower()
    text=list(text)
    textnew=text
    for i in range(len(text)):
        textnew[i]=abc[mixed.index(text[i])]
    print ''.join(textnew)
    menu()

menu()

标签: pythonpython-2.x

解决方案


if input(">>> ")==1:
    encrypt()
elif input(">>> ")==2:
    decrypt()

您正在读取elif. 这就是为什么似乎第一个命令被忽略的原因。顺便说一句,input在 Python 2 中是不安全的。您应该坚持使用raw_input(它只返回一个字符串而不尝试评估它)。

command = raw_input(">>> ")
if command=="1":
    encrypt()
elif command=="2":
    decrypt()

推荐阅读