Python打印功能输出多次

时间:2016-01-30 23:14:38

标签: python function python-3.5

我正在制作一个程序来完成certain python challenge。我创建了程序,它基本上完成了我需要它做的一切,除了它有一个奇怪的怪癖;它会多次打印我想要的输出。

cmdname = input("Enter the name of your command.\n>")
print("Enter options one by one. If the option has an argument, put a * at the end of the option. When done entering options, enter \"q\".")
oplist = ""
oplist += cmdname + " " 
def prgm(): 
    global oplist
    while 2 + 2 == 4:
        user = input(">")
        if user[0] == "-":
            if "*" in user:
                oplist += user[0:len(user) - 1] + " " 
                print("Now, enter the option's argument.")
                user = input(">")
                oplist += user[0:len(user) - 1] + " " 
                print("Option successfully added.")
                prgm()
            else: 
                oplist += user + " " 
                print("Option successfully added.")
                prgm()
        elif user == "q":
            print("Enter the command argument.")
            user = input(">")
            oplist += user
        else:
            print("Error. You didn't enter an option.")
            prgm()
        break
    print(oplist)
prgm()

输出打印的次数似乎取决于用户指定的选项数量,但我不知道为什么。另外,当在IDLE中运行程序时,如果我在函数完成后手动打印(oplist),IDLE会在一行上打印输出一次,就像我想要的那样。为什么会这样呢?

1 个答案:

答案 0 :(得分:2)

print(oplist)移到函数外部,移到程序的最后一行。由于您正在使用递归,因此多次调用此行。