Python打印函数多次输出
我正在制定一个计划来完成一项任务。我创建了这个程序,它基本上做了我需要它做的一切,除了它有一个奇怪的怪癖;它多次打印我想要的输出Python打印函数多次输出,python,function,python-3.5,Python,Function,Python 3.5,我正在制定一个计划来完成一项任务。我创建了这个程序,它基本上做了我需要它做的一切,除了它有一个奇怪的怪癖;它多次打印我想要的输出 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, en
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将在一行上打印一次输出,就像我预期的那样。为什么会出现这种情况?将
打印(oplist)
移到函数外部,移到程序的最后一行。由于使用的是递归,因此会多次调用此行。将print(oplist)
移到函数外部,直到程序的最后一行。由于您使用的是递归,因此这一行被多次调用。您可能希望提供一个使用该程序的示例,以便任何试图提供帮助的人都不必去阅读挑战网站。您输入了哪些特定命令以达到希望得到帮助的错误?不清楚此代码的目的是什么,以及使用递归和全局变量的原因。如果您传递函数参数和返回值,则更容易理解和调试您的代码。@HåkenLid:这很有效。谢谢。那么,我再补充一下。我不太确定它是否能解决这个问题,因为代码的流程有点复杂。
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()