Python printing function output multiple times

时光总嘲笑我的痴心妄想 提交于 2019-12-06 12:01:14

问题


I'm making a program to accomplish a certain python challenge. I created the program, and it basically does everything I need it to do, except it's got one weird quirk; it prints the output I want multiple times.

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

The amount of times the output is printed seems to depend on how many options the user specifies, but I don't know why. In addition, when running the program in IDLE, if I manually print(oplist) after the function is finished, IDLE prints the output once on one line, like I intended it to. Why exactly is that the case?


回答1:


Move print(oplist) outside the function, to the last line of the program. Since you are using recursion, this line is called multiple times.



来源:https://stackoverflow.com/questions/35108386/python-printing-function-output-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!