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