2

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?

ajazz
  • 83
  • 1
  • 7
  • 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. – Håken Lid Jan 30 '16 at 23:26
  • You might want to provide an example of you using the program so that anyone trying to help doesn't have to go read a challenge website. Which specific commands did you input to reach the error that you'd like help with? – Robert Rodkey Jan 30 '16 at 23:26
  • It's unclear what the purpose of this code is, and the reason why you use recursion and global variables. It would be easier to understand and debug your code if you pass function arguments and return values. – Håken Lid Jan 30 '16 at 23:29
  • @HåkenLid : That worked. Thanks. – ajazz Jan 30 '16 at 23:30
  • I'll add that as an answer, then. I wasn't quite sure if it was going to solve the problem, since the flow of the code is a bit complicated. – Håken Lid Jan 30 '16 at 23:33

1 Answers1

2

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

Håken Lid
  • 22,318
  • 9
  • 52
  • 67