gpt4 book ai didi

Python打印函数多次输出

转载 作者:太空宇宙 更新时间:2023-11-04 03:19:36 25 4
gpt4 key购买 nike

我正在编写一个程序来完成 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 会在一行上打印一次输出,就像我打算的那样。为什么会这样?

最佳答案

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

关于Python打印函数多次输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35108386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com